objective-c NSArrays的array_key_exists()和array_search()等价物是什么?

  1. I have this bug in Obj-C that is caused because the program is trying to access a non-existing NSArray key.
  2. Typically in my PHP programs I verify that a key exists before using it using array_key_exists(NEEDLE, HAYSTACK).
  3. Is there an equivalent in Cocoa / Obj-C for these two functions, and if not, how would you go about creating these.
  4. I am more interested in a solution for array_key_exists() than in array_search().

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.

Have you tried

- (BOOL)containsObject:(id)anObject

More details here

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