In an NSArray, keys can only be integers. So you can simply check whether the index you are trying to access is less than the number of items in the array. You can check the number of items via the count method:
NSArray *array = ... some array ...
NSUInteger index = ... some index ...
if (index < [array count]) {
// It's safe to do [array objectAtIndex:index]
}
You should probably look at the "Finding Objects in an Array" section of the NSArray Class Reference.
-indexOfObject:
or -indexOfObjectIdenticalTo:
might be what you're looking for.
PHP “arrays” and Cocoa “arrays” are not the same thing.
In Cocoa, an “array” is a flat, ordered collection of values. Each value's position in the array is called its index. This is the same sense as a C “array”.
In PHP, an “array” is an associative array, mapping keys to values. Another term for this is dictionary, and that is what Cocoa calls it: Cocoa's class for this is NSDictionary.
So what you want is an NSDictionary, not an NSArray.
The counterpart to array_key_exists
is objectForKey:
: If the key does not exist in the dictionary, objectForKey:
returns nil
.
The counterpart to array_search
is allKeysForObject:
.
In php, array_key_exists is for "associative" arrays or hashes, or as Objective-C calls them "Dictionaries". So you should use:
NSDictionary or NSMutableDictionary
So you could do something like this:
NSMutableDictionary *dItems = [NSMutableDictionary alloc] init] [[NSMutableDictionary alloc] init];
[dItems dItems: @"Key" forKey: @"Value"];
[dItems dItems: @"Key2" forKey: @"Value2"];
if ([dItems valueForKey: "Key"] != nil) {
// exists
}
NSDictionary is much more efficient then iterating through an array every time, and has lots
of valuable functions you can fin at: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html