Eyes, JAPAN Blog > Modern Objective-C

Modern Objective-C

will

この記事は1年以上前に書かれたもので、内容が古い可能性がありますのでご注意ください。

The period between 2 projects gave me the chance to refresh my knowledge. I picked the topic of “Modern Objective-C”. Actually, it is not new now. In WWDC 2012, there was a session introduce new feature of Objective-C. These features improve the readability and short the time for writing objective-c code.

1. Enum improvement. Developer can continue use enum with fixed underlying type or 2 keywords: NS_ENUM and NS_OPTIONS macro. Like:

typedef enum NSNumberFormatterStyle : NSUInteger {
 NSNumberFormatterNoStyle,
 NSNumberFormatterDecimalStyle,
 NSNumberFormatterCurrencyStyle,
 NSNumberFormatterPercentStyle,
 NSNumberFormatterScientificStyle,
 NSNumberFormatterSpellOutStyle
} NSNumberFormatterStyle;

or

typedef NS_ENUM(NSUInteger, NSNumberFormatterStyle) {
 NSNumberFormatterNoStyle,
 NSNumberFormatterDecimalStyle,
 NSNumberFormatterCurrencyStyle,
 NSNumberFormatterPercentStyle,
 NSNumberFormatterScientificStyle,
 NSNumberFormatterSpellOutStyle
};

NS_OPTIONS is the macro to define bitmask. Can be used for define the status.

typedef NS_OPTIONS(NSUInteger, Arrows) {
    ArrowNone      = 0,
    ArrowRight     = 1 << 0,
    ArrowBottom    = 1 << 1,
    ArrowLeft      = 1 << 2,
    ArrowTop       = 1 << 3
};

To use the status:

Arrows a = (ArrowLeft | ArrowRight);
if (a & ArrowBottom) {
   NSLog(@"arrow bottom code here");
}

if (a & ArrowLeft) {
   NSLog(@"arrow left code here");
}

if (a & ArrowRight) {
   NSLog(@"arrow right code here");
}

if (a & ArrowTop) {
   NSLog(@"arrow top code here");
}

2. Synthesise by default. Developer don’t need to write @synthesize in the implementation file anymore. The synthesise will be done by default. In the implementation file, the instance variables can be accessed prefixed with “_” to improve the readability. 3. Object literal. Previously to assign a value to an object. Because there is not auto box mechanism in objective-c, developer needs to type quite a lot of code like:

NSNumber *number1 = [[NSNumber alloc] initWithDouble:12.0];

From now developer just types

NSNumber *number1 = @12.0;

is enough. The expression prefixed with “@” is object literal. Literal can be even use for expression, Array, Dictionary. Like:

NSNumber *piOverSixteen = @( M_PI / 16 );
NSNumber *hexDigit = @( "012345679ABCDEF"[i % 16] );
NSArray *array = @[ a, b, c ];
NSDictionary *dict = @{ k1 : o1, k2 : o2, k3 : o3 };

4. Object Subscripting.

@implementation Database {
 NSMutableDictionary *_storage;
}
- (id)replaceObject:(id)newObject forKey:(id )key {
 id oldObject = _storage[key];
 _storage[key] = newObject;
 return oldObject;
}
  • このエントリーをはてなブックマークに追加

Comments are closed.