New Objective-C Literal Syntax for NSArray, NSDictionary

Users of Apple compiler releases can use these features starting with the Apple LLVM Compiler 4.0. Users of open-source LLVM.org compiler releases can use these features starting with clang v3.1.

NSNumber literals
NSNumber *n1 = @1000;  // [NSNumber numberWithInt:1000] 
NSNumber *n2 = @3.1415926; // [NSNumber numberWithDouble:3.1415926]
NSNumber *c = @'c'; // [NSNumber numberWithChar:'c']
NSNumber *b = @YES; // [NSNumber numberWithBool:YES]

// uses the usual suffixes for `unsigned` (`u`) and `float` (`f`)
NSNumber *f = @2.5f;
NSNumber *nu = @256u;

 

NSArray literals

// before
NSArray *words = [NSArray arrayWithObjects:@"list", @"of", @"words",[NSNumber numberWithInt:123],[NSNumber numberWithFloat:3.14], nil];
// after (array with some strings and numbers)
NSArray *words = @[@"list", @"of", @"words", @123, @3.14];

不需要nil结尾

 

NSDictionary literals

NSDictionary *d = @{
  @"key": @"value",
  @"name": @"Joris",
  @"n": @1234,
  @3: @"string"
};

   不需要nil结尾

 

 

NSMutableArray *array = ...;
NSUInteger idx = ...;
id newObject = ...;
id oldObject = array[idx];
array[idx] = newObject;		    // replace oldObject with newObject

NSMutableDictionary *dictionary = ...;
NSString *key = ...;
oldObject = dictionary[key];
dictionary[key] = newObject;	// replace oldObject with newObject
 

 

 

详情:http://clang.llvm.org/docs/ObjectiveCLiterals.html

 

你可能感兴趣的:(Objective-C)