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.
As in, NSArray *obj = [NSArray ...]; id item = obj[0];
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];
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"];
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];
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];
EDIT:
Far more detailed answer than mine here: What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?
EDIT 2:
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.
EDIT 3:
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.
It is not possible, unfortunately (or not).
The only option you have is to build a C++ wrapper around NSArray
and override operator[]
.
Then, all of your files that use that wrapper should be Objective-C++ (i.e., use the .mm extension) to be correctly compiled.
EDIT:
An update to this answer. As of Xcode 4.5/iOS 6, it is possible to user subscript notation to access an NSArray elements:
NSArray* array = ...;
id val = array[i];
This is the official Xcode 4.5 release notes wording:
Support for subscripting using '[ ]' syntax with Objective-C container objects are supported for iOS 6.0.
(Thanks to Nick Lockwood for his comment below)
Nope. You can, however, extract the NSArray's contents into a C array and then use the subscript operator with that.