Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More convenient NSArray and NSDictionary access

Tags:

objective-c

Note that this is merely an academic question.

In Ruby, you can access array and dictionary(hash) elements conveniently:

value = myHash['myKey']

In Objective C, you need a method call:

value = [myDict objectForKey:@"myKey"];

How might one override some type of brackets or define a macro to bring the Objective C syntax closer to Ruby's?

like image 881
Peter DeWeese Avatar asked Jan 22 '26 01:01

Peter DeWeese


2 Answers

Just an update:

Starting with iOS 6 I guess, you CAN use such a syntax:

value = dictionary[@"key"];

This is equivalent to

value = [dictionary objectForKey:@"key"];

Moreover, if we're talking about NSMutableDictionary, you can add new objects into a dictionary like this:

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
dictionary[@"a"] = @"A";
NSLog(@"%@",dictionary[@"a"]);
like image 148
Maxim Chetrusca Avatar answered Jan 23 '26 13:01

Maxim Chetrusca


What you are trying to do requires a language feature called "operator overloading". Objective-C does not allow for operator overloading because the designers of the language felt that operator overloading was harmful more often than it was helpful.

C++ does allow for operator overloading, so one way to get the syntax you want is to wrap your collections in C++ classes and use those instead. To switch to Objective-C++, just change your implementation files' extensions from .m to .mm.

Personally, I would recommend against using C++ wrappers around collections because it will make your code harder for other Objective-C programmers to read and it will break some of the more advanced features of Xcode. For example, you will no longer be able to use the refactor tools, because Xcode will not be able to parse your code correctly.

like image 36
Nathan Avatar answered Jan 23 '26 15:01

Nathan