The 10 Most Common Mistakes iOS Developers Don’t Know They’re Making

What’s the only thing worse than having a buggy app rejected by the App Store? Having it accepted. Once the one-star reviews start rolling in, it’s almost impossible to recover. This costs companies money and developers their jobs.

iOS is now the second-largest mobile operating system in the world. It also has a very high adoption rate, with more than 85% of users on the latest version. As you might expect, highly engaged users have high expectations—if your app or update isn’t flawless, you’ll hear about it.

With the demand for iOS developers continuing to skyrocket, many engineers have switched to mobile development (more than 1,000 new apps are submitted to Apple every day). But true iOS expertise extends far beyond basic coding. Below are 10 common mistakes that iOS developers fall prey to, and how you can avoid them.

85% of iOS users use the latest OS version.
That means they expect your app or update to be flawless.

Common Mistake #1: Not Understanding Asynchronous Processes

A very common type of mistake among new programmers is handling asynchronous code improperly. Let’s consider a typical scenario: User opens a screen with the table view, some data is fetched from the server and displayed in a table view. We can write it more formally:

At first glance, everything looks right: We fetch data from the server and then update the UI. However, the problem is fetching data is an asynchronous process, and won’t return new data immediately, which means reloadData will be called before receiving the new data. To fix this mistake, we should move line #2 right after line #1 inside the block.

However, there may be situations where this code still does not behave as expected, which brings us to …

Common Mistake #2: Running UI-Related Code on a Thread Other than the Main Queue

Let’s imagine we used corrected code example from the previous common mistake, but our table view is still not updated with the new data even after the asynchronous process has successfully completed. What might be wrong with such simple code? To understand it, we can set a breakpoint inside the block and find out on which queue this block is called. There is a high chance the described behavior is happening because our call is not in the main queue, where all UI-related code should be performed.

Most popular libraries—such as Alamofire, AFNetworking, and Haneke—are designed to call completionBlockon the main queue after performing an asynchronous task. However, you can’t always rely on this and it is easy to forget to dispatch your code to the right queue.

To make sure all your UI-related code is on the main queue, don’t forget to dispatch it to that queue:

Common Mistake #3: Misunderstanding Concurrency & Multithreading

Concurrency could be compared to a really sharp knife: You can easily cut yourself if you’re not careful or experienced enough, but it’s extremely useful and efficient once you know how to use it properly and safely.

You can try to avoid using concurrency, but no matter what kind of apps you’re building, there is really high chance you can’t do without it. Concurrency can have significant benefits for your application. Notably:

Almost every application has calls to web services (for example, to perform some heavy calculations or read data from a database). If these tasks are performed on the main queue, the application will freeze for some time, making it non-responsive. Moreover, if this takes too long, iOS will shut down the app completely. Moving these tasks to another queue allows the user to continue use the application while the operation is being performed without the app appearing to freeze.

Modern iOS devices have more than one core, so why should the user wait for tasks to finish sequentially when they can be performed in parallel?

But the advantages of concurrency don’t come without complexity and the potential for introducing gnarly bugs, such as race conditions that are really hard to reproduce.

Let’s consider some real-world examples (note that some code is omitted for simplicity).

At first glance, everything is synced and appears as if it should work as expected, since ThreadSaveVar wraps counter and makes it thread safe. Unfortunately, this is not true, as two threads might reach the increment line simultaneously and counter.value == someValue will never become true as a result. As a workaround, we can make ThreadSafeCounter which returns its value after incrementing:

In this case, dispatch_barrier_sync was used to sync access to the array. This is a favorite pattern to ensure access synchronization. Unfortunately, this code doesn’t take into account that struct makes a copy each time we append an item to it, thus having a new synchronization queue each time.

Here, even if it looks correct at first sight, it might not work as expected. It also requires a lot of work to test and debug it, but in the end, you can improve your app speed and responsiveness.

Common Mistake #4: Not Knowing Pitfalls of Mutable Objects

Swift is very helpful in avoiding mistakes with value types, but there are still a lot of developers who use Objective-C. Mutable objects are very dangerous and can lead to hidden problems. It is a well-known rule that immutable objects should be returned from functions, but most developers don’t know why. Let’s consider the following code:

The expectation here is that [newChildBoxes count] > [childBoxes count], but what if it is not? Then the class is not well designed because it mutates a value that was already returned. If you believe that inequality should not be true, try experimenting with UIView and [view subviews].

Luckily, we can easily fix our code, by rewriting the getter from the first example:

- (NSArray *)boxes {
return [self.m_boxes copy];
}

Common Mistake #5: Not Understanding How iOS NSDictionary Works Internally

If you ever worked with a custom class and NSDictionary, you might realize you cannot use your class if it doesn’t conform to NSCopying as a dictionary key. Most developers have never asked themselves why Apple added that restriction. Why does Apple copy the key and use that copy instead of the original object?

The key to understanding this is figuring out how NSDictionary works internally. Technically, it’s just a hash table. Let’s quickly recap how it works on a high level while adding an Object for a Key (table resizing and performance optimization is omitted here for simplicity):

Step 1: It calculates hash(Key).
Step 2: Based on the hash, it looks for a place to put the object. Usually, this is done by taking the modulus of the hash value with the dictionary length. The resulting index is then used to store the Key/Value pair.
Step 3: If there is no object in that location, it creates a linked list and stores our Record (Object and Key). Otherwise, it appends Record to the end of the list.

Now, let’s describe how a record is fetched from the dictionary:

Step 1: It calculates hash(Key).
Step 2: It searches a Key by hash. If there is no data, nil is returned.
Step 3: If there is a linked list, it iterates through the Object until [stored_key isEqual:Key].

With this understanding of what is occurring under the hood, two conclusions can be drawn:

If the Key’s hash changes, Record should be moved to another linked list.

What should happen with our dictionary? As the name was mutated, we now have a different hash. Now our Object lies in the wrong place (it still has the old hash value, as the Dictionary doesn’t know about the data change), and it’s not really clear what hash we should use to lookup data in the dictionary. There could be an even worse case. Imagine if we already had “Jon Snow” in our dictionary with a rating of 5. The dictionary would end up with two different values for the same Key.

As you can see, there are many problems that can arise from having mutable keys in NSDictionary. The best practice to avoid such issues is to copy the object before storing it, and to mark properties as copy. This practice will also help you to keep your class consistent.

Common Mistake #6: Using Storyboards Instead of XIBs

Most new iOS developers follow Apple’s suggestion and use Storyboards by default for the UI. However, there are a lot of drawbacks and only a few (debatable) advantages in using Storyboards.

Storyboard drawbacks include:

It’s really hard to modify a Storyboard for several team members. Technically, you can use many Storyboards, but the only advantage, in that case, is making it possible to have segues between controllers on the Storyboard.

Controllers and segues names from Storyboards are Strings, so you have to either re-enter all those Strings throughout your code (and one day you will break it), or maintain a huge list of Storyboard constants. You could use SBConstants, but renaming on the Storyboard is still not an easy task.

Storyboards force you into a non-modular design. While working with a Storyboard, there is very little incentive to make your views reusable. This may be acceptable for the minimum viable product (MVP) or quick UI prototyping, but in real applications you might need to use the same view several times across your app.

Storyboard (debatable) advantages:

The whole app navigation can be seen at a glance. However, real applications can have more than ten controllers, connected in different directions. Storyboards with such connections look like a ball of yarn and don’t give any high-level understanding of data flows.

Static tables. This is the only real advantage I can think of. The problem is that 90 percent of static tables tends to turn into dynamic tables during app evolution and a dynamic table can be more easily handled by XIBs.

Common Mistake #7: Confusing Object & Pointer Comparison

While comparing two objects, we can consider two equality: pointer and object equality.

Pointer equality is a situation when both pointers point to the same object. In Objective-C, we use ==operator for comparing two pointers. Object equality is a situation when two objects represent two logically identical objects, like the same user from a database. In Objective-C, we use isEqual, or even better, type specific isEqualToString, isEqualToDate, etc. operators for comparing two objects.

#define is a preprocessor macro that replaces the named definition with its value in the code. So, if you have #define in a header file and import it somewhere, all occurrences of the defined value in that file will be replaced too.

This works well, except for one issue. To illustrate the remaining problem, consider the following code:

#define X = 3
...
CGFloat y = X / 2;

What would you expect the value of y to be after this code executes? If you said 1.5, you are incorrect. y will be equal to 1 (not 1.5) after this code executes. Why? The answer is that #define has no information about the type. So, in our case, we have a division of two Int values (3 and 2), which results in an Int (i.e., 1) which is then cast to a Float.

This can be avoided by using constants instead which are, by definition, typed:

This code works as intended, allowing only Admin users to be able to change other records. However, what might happen we add another user type Manager that should be able to edit records as well? If we forget to update this switch statement, the code will compile, but it will not work as expected. However, if the developer used enum values instead of the default keyword from the very beginning, the oversight will be identified at compile time, and could be fixed before going to test or production. Here is the good way to handle this in Objective-C:

Common Mistake #10: Using NSLog for Logging

Many iOS developers use NSLog in their apps for logging, but most of the time this is a terrible mistake. If we check the Apple documentation for the NSLog function description, we will see it is very simple:

voidNSLog(NSString *format, ...);

What could possibly go wrong with it? In fact, nothing. However, if you connect your device to the XCode Organizer, you’ll see all your debug messages there. For this reason alone, you should never use NSLog for logging: it’s easy to show some unwanted internal data, plus it looks unprofessional.