Friday, July 25, 2014

Modern Objective c



Use 'Modern Objective-C Syntax'

Objective-C makes heavy use of the @ operator, which generally denotes Objective-C objects. For example, "string" is a char*, while @"string" is an NSString. These have been standard in Objective-C for a long time, but only recently, in Objective-C 2.0, did Apple add in definitions for NSDictionary, NSArray, and NSNumber, all using literals specified with @ directives.

-----------------------------------------------------------------------------------------------------
NSNumber *number = [NSNumber numberWithInteger:7];
NSNumber *modernNumber = @(7); // or @7
-----------------------------------------------------------------------------------------------------
NSArray *array = [NSArray arrayWithObjects:number, modernNumber, nil];
NSArray *modernArray = @[number, modernNumber];
-----------------------------------------------------------------------------------------------------
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:number, @"number"];
NSDictionary *modernDictionary = @{@"number" : number};
-----------------------------------------------------------------------------------------------------


It's more concise, and still somehow more readable.


Enum 

Replace your enum declarations, such as this one:
enum {

        UITableViewCellStyleDefault,

        UITableViewCellStyleValue1,

        UITableViewCellStyleValue2,

        UITableViewCellStyleSubtitle

};

typedef NSInteger UITableViewCellStyle;


with the NS_ENUM syntax:



typedef NS_ENUM(NSInteger, UITableViewCellStyle) {

        UITableViewCellStyleDefault,

        UITableViewCellStyleValue1,

        UITableViewCellStyleValue2,

        UITableViewCellStyleSubtitle

};


But when you use enum to define a bitmask, such as here:

enum {

        UIViewAutoresizingNone                 = 0,

        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,

        UIViewAutoresizingFlexibleWidth        = 1 << 1,

        UIViewAutoresizingFlexibleRightMargin  = 1 << 2,

        UIViewAutoresizingFlexibleTopMargin    = 1 << 3,

        UIViewAutoresizingFlexibleHeight       = 1 << 4,

        UIViewAutoresizingFlexibleBottomMargin = 1 << 5

};
typedef NSUInteger UIViewAutoresizing;

use the NS_OPTIONS macro.


typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {

        UIViewAutoresizingNone                 = 0,

        UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,

        UIViewAutoresizingFlexibleWidth        = 1 << 1,

        UIViewAutoresizingFlexibleRightMargin  = 1 << 2,

        UIViewAutoresizingFlexibleTopMargin    = 1 << 3,

        UIViewAutoresizingFlexibleHeight       = 1 << 4,

        UIViewAutoresizingFlexibleBottomMargin = 1 << 5

};

Alternatively, you can use the modern Objective-C converter in Xcode to make this change to your code automatically. 

No comments:

Post a Comment