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.
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:
@property (nonatomic, strong) NSArray *dataFromServer;
- (void)viewDidLoad {
__weak __typeof(self) weakSelf = self;
[[ApiManager shared] latestDataWithCompletionBlock:^(NSArray *newData, NSError *error){
weakSelf.dataFromServer = newData; // 1
}];
[self.tableView reloadData]; // 2
}
// and other data source delegate methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataFromServer.count;
}
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.
@property (nonatomic, strong) NSArray *dataFromServer;
- (void)viewDidLoad {
__weak __typeof(self) weakSelf = self;
[[ApiManager shared] latestDataWithCompletionBlock:^(NSArray *newData, NSError *error){
weakSelf.dataFromServer = newData; // 1
[weakSelf.tableView reloadData]; // 2
}];
}
// and other data source delegate methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataFromServer.count;
}
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 completionBlock
on 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:
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
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).
Case 1
final class SpinLock {
private var lock = OS_SPINLOCK_INIT
func withLock<Return>(@noescape body: () -> Return) -> Return {
OSSpinLockLock(&lock)
defer { OSSpinLockUnlock(&lock) }
return body()
}
}
class ThreadSafeVar<Value> {
private let lock: ReadWriteLock
private var _value: Value
var value: Value {
get {
return lock.withReadLock {
return _value
}
}
set {
lock.withWriteLock {
_value = newValue
}
}
}
}
The multithreaded code:
let counter = ThreadSafeVar<Int>(value: 0)
// this code might be called from several threads
counter.value += 1
if (counter.value == someValue) {
// do something
}
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:
class ThreadSafeCounter {
private var value: Int32 = 0
func increment() -> Int {
return Int(OSAtomicIncrement32(&value))
}
}
Case 2
struct SynchronizedDataArray {
private let synchronizationQueue = dispatch_queue_create("queue_name", nil)
private var _data = [DataType]()
var data: [DataType] {
var dataInternal = [DataType]()
dispatch_sync(self.synchronizationQueue) {
dataInternal = self._data
}
return dataInternal
}
mutating func append(item: DataType) {
appendItems([item])
}
mutating func appendItems(items: [DataType]) {
dispatch_barrier_sync(synchronizationQueue) {
self._data += items
}
}
}
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:
// Box.h
@interface Box: NSObject
@property (nonatomic, readonly, strong) NSArray <Box *> *boxes;
@end
// Box.m
@interface Box()
@property (nonatomic, strong) NSMutableArray <Box *> *m_boxes;
- (void)addBox:(Box *)box;
@end
@implementation Box
- (instancetype)init {
self = [super init];
if (self) {
_m_boxes = [NSMutableArray array];
}
return self;
}
- (void)addBox:(Box *)box {
[self.m_boxes addObject:box];
}
- (NSArray *)boxes {
return self.m_boxes;
}
@end
The code above is correct, because NSMutableArray
is a subclass of NSArray
. So what can go wrong with this code?
The first and the most obvious thing is that another developer might come along and do the following:
NSArray<Box *> *childBoxes = [box boxes];
if ([childBoxes isKindOfClass:[NSMutableArray class]]) {
// add more boxes to childBoxes
}
This code will mess up your class. But in that case, itโs a code smell, and itโs left up to that developer to pick up the pieces.
Here is the case, though, that is much worse and demonstrates an unexpected behavior:
Box *box = [[Box alloc] init];
NSArray<Box *> *childBoxes = [box boxes];
[box addBox:[[Box alloc] init]];
NSArray<Box *> *newChildBoxes = [box boxes];
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.
- Keys should be unique.
Letโs examine this on a simple class:
@interface Person
@property NSMutableString *name;
@end
@implementation Person
- (BOOL)isEqual:(id)object {
if (self == object) {
return YES;
}
if (![object isKindOfClass:[Person class]]) {
return NO;
}
return [self.name isEqualToSting:((Person *)object).name];
}
- (NSUInteger)hash {
return [self.name hash];
}
@end
Now imagine NSDictionary
doesnโt copy Keys:
NSMutableDictionary *gotCharactersRating = [[NSMutableDictionary alloc] init];
Person *p = [[Person alloc] init];
p.name = @"Job Snow";
gotCharactersRating[p] = @10;
Oh! We have a typo there! Letโs fix it!
p.name = @"Jon Snow";
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.
Consider the following code:
NSString *a = @"a"; // 1
NSString *b = @"a"; // 2
if (a == b) { // 3
NSLog(@"%@ is equal to %@", a, b);
} else {
NSLog(@"%@ is NOT equal to %@", a, b);
}
What will be printed out to the console when we run that code? We will get a is equal to b
, as both objects a
and b
are pointing to the same object in memory.
But now letโs change line #2 to:
NSString *b = [[@"a" mutableCopy] copy];
Now we get a is NOT equal to b
since these pointers are now pointing to different objects even though those objects have the same values.
This problem can be avoided by relying on isEqual
, or type specific functions. In our code example, we should replace line #3 with following code for it to always work properly:
if ([a isEqual:b]) {
Common Mistake #8: Using Hardcoded Values
There are two primary problems with hardcoded values:
- Itโs often not clear what they represent.
- They need to be re-entered (or copied and pasted) when they need to be used in multiple places in the code.
Consider the following example:
if ([[NSDate date] timeIntervalSinceDate:self.lastAppLaunch] < 172800) {
// do something
}
or
[self.tableView registerNib:nib forCellReuseIdentifier:@"SimpleCell"];
...
[self.tableView dequeueReusableCellWithIdentifier:@"SimpleCell"];
What does 172800 represent? Why is it being used? It is probably not obvious that this corresponds to the number of seconds in 2 days (there are 24 x 60 x 60, or 86,400, seconds in a day).
Rather than using hardcoded values, you could define a value using the #define
statement. For example:
#define SECONDS_PER_DAY 86400
#define SIMPLE_CELL_IDENTIFIER @"SimpleCell"
#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:
static const CGFloat X = 3;
...
CGFloat y = X / 2; // y will now equal 1.5, as expected
Common Mistake #9: Using Default Keyword in a Switch Statement
Using the default
keyword in a switch statement can lead to bugs and unexpected behavior. Consider the following code in Objective-C:
typedef NS_ENUM(NSUInteger, UserType) {
UserTypeAdmin,
UserTypeRegular
};
- (BOOL)canEditUserWithType:(UserType)userType {
switch (userType) {
case UserTypeAdmin:
return YES;
default:
return NO;
}
}
The same code written in Swift:
enum UserType {
case Admin, Regular
}
func canEditUserWithType(type: UserType) -> Bool {
switch(type) {
case .Admin: return true
default: return false
}
}
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:
typedef NS_ENUM(NSUInteger, UserType) {
UserTypeAdmin,
UserTypeRegular,
UserTypeManager
};
- (BOOL)canEditUserWithType:(UserType)userType {
switch (userType) {
case UserTypeAdmin:
case UserTypeManager:
return YES;
case UserTypeRegular:
return NO;
}
}
The same code written in Swift:
enum UserType {
case Admin, Regular, Manager
}
func canEditUserWithType(type: UserType) -> Bool {
switch(type) {
case .Manager: fallthrough
case .Admin: return true
case .Regular: return false
}
}
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:
void NSLog(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.
Better approach is to replace NSLogs
with configurable CocoaLumberjack or some other logging framework.
Wrap Up
iOS is a very powerful and rapidly evolving platform. Apple makes a massive ongoing effort to introduce new hardware and features for iOS itself, while also continually expanding the Swift language.
Improving your Objective-C and Swift skills will make you a great iOS developer and offer opportunities to work on challenging projects using cutting-edge technologies.
Discover more from TechBooky
Subscribe to get the latest posts sent to your email.