Domanda

I am going to store a list of values in a plist and retrieve them. The list will be searched for a value (which may change each time) each time the search method is called. There will probably be about 10 values in the list.

Is either NSArray or NSDictionary better for a search?

I think that NSArray is more appropriate because right now, at least, I don't have a key-value pair data set, just a list.

Could someone confirm and perhaps offer the best method for search the array?

Thanks

È stato utile?

Soluzione

The problem is conceptual:

If you have a list of value, you mustn't use NSDictionary. The appropriate data structure is NSArray or NSSet.

Basically, NSSet is faster than NSArray, because doesn't have to consider the order etc.

So if you need just to search a value and the order doesn't matter, the best data structure to use is NSSet (or NSMutableSet if you need it mutable).

Altri suggerimenti

Dictionaries will be faster for searching than arrays because the keys are hashed. With an array the system has to check all the items until it finds a match.

The docs for NSSet say that sets are faster in testing for membership than arrays. If you don't have values to store for each key, the best option might be to store the data to your plist as an array. At runtime, read the array, and load it's contents into a set using the NSSet class method setWithArray:

If your data sets are large (many thousands of items) I would suggest doing performance testing with dictionaries where all the values are NSNull against an NSSet. (With a dictionary you'd use objectForKey: and with a set you'd use the containsObject: method

Ignoring timing the best option would be to use an NSArray. NSArray has all sorts of useful methods such as

(NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate

and

(NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate

that you can use for searching within an array.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top