Objective-C : Do This, Not That

xcode6_graphics

Below is my Objective-C niggle list. Beyond listing my niggles, I’ve also included what I think is a proper resolution for each complaint and why I think it is a correct resolution. I’d love to hear from anybody who disagrees and why they disagree.

I should note that I’ve, at some point in the past, committed some (probably all) of the Objective-C coding sins I’ve called out below. whattayagunnado…


 

Constants

Instead of this:

1
2
#define FRAME_MARGIN_TOP 50
#define FRAME_MARGIN_BOTTOM 50

Do this:

1
2
static const NSInteger kFrameMarginTop = 50;
static const NSInteger kFrameMarginBottom = 50;

Here’s Why:
The macro doesn’t explicitly indicate any type information.

 


 

Literals

Instead of this:

1
2
3
4
NSNumber *myNumber = [NSNumber numberWithInteger:42];
NSArray *myHeroes = [NSArray arrayWithObjects:@"Superman", @"Spiderman", nil];
NSMutableArray *myOtherHeroes = [NSMutableArray arrayWithObjects:@“Black Panther”, @"Moon Knight", nil];
NSDictionary *myContacts = [NSDictionary dictionaryWithObjectsAndKeys:@"John", @"FirstName", @"Doe", @"LastName", nil];

Do this:

1
2
3
4
NSNumber *myNumber = @42;
NSArray *myHeroes = @[@“Superman", @"Spiderman"];
NSMutableArray *myOtherHeroes2 = [@[@"Aquaman", @"Moon Knight"] mutableCopy];
NSDictionary *myContacts = @{@"FirstName":@"John", @"LastName":@"Doe"};

Here’s Why:
The literal syntax is easier on the eyes. Not using the literal syntax signals that you’ve stopped paying attention to the advances in clang before 2012.

 


 

Enumerations

Instead of this:

1
2
3
4
5
enum BroadcastState{
    BroadcastStateDisconnected,
    BroadcastStateDataRecieved
};
typedef enum BroadcastState BroadcastState;

Do this:

1
2
3
4
typedef NS_ENUM(NSUInteger, BroadcastState) {
    BroadcastStateDisconnected,
    BroadcastStateDataRecieved
};

Here’s Why:
The NS_ENUM macro’s enumeration type is explicit.

 


 

No ops

Instead of this:

1
2
if( someVar != nil )
  [someVar doSomething];

Do this:

1
[someVar doSomething];

Here’s Why:
Sending a message to a nil object is a no-op.

 


 

Leave a Reply

Your email address will not be published. Required fields are marked *