使用下标访问NSArray的项目

Dav*_*vid 7 cocoa objective-c nsarray xcode4

是否可以使用[idx]访问NSArray的对象?我有一个使用[]样式索引的标准库,我不想重写整个库以适应ObjC的objectAtIndex:方法.

如, NSArray *obj = [NSArray ...]; id item = obj[0];

Nic*_*ood 20

接受的答案(当时是真的)现在已经过时了.从Xcode 4.5开始,您现在可以使用以下命令设置和获取NSArray元素:

id object = array[5]; // equivalent to [array objectAtIndex:5];
mutableArray[5] = object; // equivalent to [mutableArray replaceObjectAtIndex:5 withObject:object];
Run Code Online (Sandbox Code Playgroud)

你也可以使用以下方法为NSDictionaries做同样的事情:

id object = dict[@"key"]; // equivalent to [dict objectForKey:@"key"];
mutableDict[@"key"] = object; // equivalent to [mutableDict setObject:object forKey:@"key"];
Run Code Online (Sandbox Code Playgroud)

更酷的是,您现在可以使用类似JSON的语法创建数组和字典对象:

NSArray *array = @[@"value1", @"value2"]; // equivalent to [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dict = @{@"key1":@"value1", @"key2":@"value2"}; // equivalent to [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
Run Code Online (Sandbox Code Playgroud)

类似地,像NSNumber这样的盒装值现在可以用简写语法编写:

NSNumber *intNumber = @5; // equivalent to [NSNumber numberWithInteger:5];
NSNumber *boolNumber = @YES; // equivalent to [NSNumber numberWithBool:YES];
NSNumber *someNumber = @(variable); // equivalent to [NSNumber numberWithWhatever:variable];
Run Code Online (Sandbox Code Playgroud)

编辑:

比我的更详细的答案:Xcode 4.4发行说明中提到的"Objective-C Literals"的细节是什么?

编辑2:

需要说明的是,虽然在Xcode 4.5之前没有添加此功能,但它适用于iOS 4.3及更高版本,因此如果您需要支持较旧的iOS版本,则不必避免使用此功能.

编辑3:

为了迂腐精确,它适用于Apple LLVM编译器4.1及更高版本.AKA Xcode 4.5附带的版本.

  • ``mutableArray [5] =对象; //等价于[mutableArray replaceObjectAtIndex:5 withObject:object];``不是真的.它相当于``setObject:(id)anObject atIndexedSubscript:(NSUInteger)index`` (2认同)