使用下标访问NSArray的项目 [英] Accessing NSArray's items with subscript

查看:91
本文介绍了使用下标访问NSArray的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to access NSArray's objects using [idx]? I have a standard library that uses [] style indexing and I don't want to rewrite the whole library to suit ObjC's objectAtIndex: method.

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

推荐答案

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

The accepted answer (whilst true at the time) is now out of date. As of Xcode 4.5, you can now set and get NSArray elements using:

id object = array[5]; // equivalent to [array objectAtIndex:5];
mutableArray[5] = object; // equivalent to [mutableArray replaceObjectAtIndex:5 withObject:object];

您也可以使用以下方法对NSDictionaries进行相同操作:

You can also do the same for NSDictionaries using:

id object = dict[@"key"]; // equivalent to [dict objectForKey:@"key"];
mutableDict[@"key"] = object; // equivalent to [mutableDict setObject:object forKey:@"key"];

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

Even cooler, you can now create array and dictionary objects using JSON-like syntax:

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];

类似地,像NSNumber这样的带框值现在可以用简写形式编写:

And in a similar vein, boxed values like NSNumber can now be written in a shorthand syntax:

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

编辑:

更详细的答案比我这里的要好: Objective-C文字的详细信息是什么?在Xcode 4.4发行说明中提到过?

Far more detailed answer than mine here: What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?

编辑2:

不过此功能直到Xcode 4.5才被添加,它可以在iOS 4.3及更高版本上运行,因此如果您需要支持较旧的iOS版本,则不必避免使用此功能。

To be clear, though this feature wasn't added until Xcode 4.5, it works on iOS 4.3 and above, so you don't have to avoid using this if you need to support older iOS versions.

编辑3:

出于书呆子的精确性,它适用于Apple LLVM编译器4.1及更高版本。也就是Xcode 4.5附带的版本。

For the sake of pedantic precision, it works on Apple LLVM compiler version 4.1 and above. AKA the version that shipped with Xcode 4.5.

这篇关于使用下标访问NSArray的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆