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
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).
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.
Related
I am looking for the type or data structure to store a big number of same type primitives on my app (Mac OS X or iOS) using Objective C. As I understood NSNumber stores only one primitive (correct me if I am wrong). I have, let's say, thousands of integers or strings. Which would be the best solution to put, store and access them there? NSSet, NSArray, NSMutableArray, NSDictionary, NSMutableDictionary or something else? I know that they have different features, but I care basically only about the performance of basic operations (putting, storing, retrieving).
It only depends on how you want to ADD, STORE and REMOVE this data.
First Let us go through each type of Data Structure that is available to us in Objective-C:
Primitive Array
This is the most basic type of storage in Objective-C(or C) which is used to store primitives.
Ex: int a[4] = {1, 2, 3, 4};
The limitation to this is
Can only store primitive types.
Array size cannot be changed once declared.
Can only be retrieved by its index.
Can store only single type of data, defined at the time of declaring the array.
NSArray
This is a container for storing objects. Any object which is of type NSObject (or inherits from NSObject) or is of type 'id' can be stored in NSArray.
Once initialized, it cannot be mutated i.e. array size cannot be changed nor the objects it contains can be modified. This is good in terms of security.
Objects can only be accessed by its index.
NSMutableArray
Same as NSArray, but
Can be mutated, i.e. the existing objects can be modified and also new objects can be added or deleted.
NSSet
Same as NSArray but
Stores only unique objects.
Objects cannot be accessed by its index. Objects can only be accessed by enumeration.
NSMutableSet
Same as NSSet, but
Can be mutated, i.e. objects can be added or removed at a later point of time.
NSOrderedSet
Same as NSArray, i.e. objects are stored and retrieved by an index, but
Stores only unique objects.
NSMutableOrderedSet
Same as NSMutableArray, but
Stores only unique objects.
NSDictionary
Can store any type of data.
Objects are stored and retrieved by a key.
Once initialized, cannot be mutated i.e. cannot add new key-values nor can update existing objects associated to a particular key.
NSMutableDictionary
Same as NSDictionary
Can be mutated, i.e. new objects can be added or removed and existing objects can be modified.
This was a short description about mostly used Data Structures in Objective-C. These are used based on the need of the program and how data is to be manipulated.
Therefore,
If you want to store thousands of numbers and strings and want access it by its index value then use NSMutableArray. If you are not going to add, remove or modify any objects in the future then use NSArray.
If you want to store data but do not want duplicates and want to access it by its index the use NSOrderedSet/NSMutableOrderedSet
If you want to store data but do not want duplicates and its order also doesn't matter then use NSSet/NSMutableSet.
If you want to access data by a particular key then use NSDictionary/NSMutableDictionary
Regarding Performance
Since NSSet doesn't contain any order, they are more performant than NSArray
Here is a very good and detailed article on performance characteristics for each Data Structure discussed above
Class Time [ms] 1,000,000 elements
Adding
NSMutableOrderedSet 3190.52
NSMutableDictionary 2522.47
NSMutableSet 2511.96
NSMutableArray 1423.26
NSSet 8.03
Random Access
NSMutableOrderedSet 10.74
NSMutableDictionary 9.18
NSMutableArray 8.08
NSMutableSet 4.47
NSSet 3.56
To know more about Objective-C Data Types and Data Structure, read this
i am new to iOS. Anyone know if NSSet are faster than NSArray? Why wouldn't I always just use an NSArray?
Anyone explain me difference between NSSet and NSArray?
NSSet is used to have unique objects.
NSArray may have duplicate objects.
NSSet is an unordered collection.
NSArray is an ordered collection.
NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating. if you only need to iterate contents, don't use an NSSet.
When the order of the items in the collection is not important, sets offer better performance for finding items in the collection.
The reason is that a set uses hash values to find items (like a dictionary) while an array has to iterate over its entire contents to find a particular object.
More detailed information here:
http://www.cocoawithlove.com/2008/08/nsarray-or-nsset-nsdictionary-or.html
When the order of elements isn’t important and performance of testing whether an object is in the set is important. Even though arrays are ordered, testing them for membership is slower than testing sets.
quick question. I have two NSMutableArray:
Array 1: [A,B,C,D,E,F];
Array 2: [B,E,F];
Note that Array 2 is always subset of Array 1 - meaning objects that exist is Array 2, definitely exist is Array 1 as well.
So what I want is to build an array that contain the objects that are NOT in Array 2. Like so
Array 3: [A,C,D];
I've tried using relative complement as outlined in this post but the resulting array is basically the same as Array 1. It doesn't eliminate the objects that exist in Array 2.
I also tried the answer here as well, but still not getting what I want. Unless i'm really doing something very obviously wrong.
Using NSPredicate is much preferable, I guess. But I'm open to ideas and hints.
Note: Just for context, i'm doing this to update my UITableView, basically for data filtering purposes.
Thanks!
UPDATE
So all the answers given so far actually works with simple set of dummy data for me. But when I tested with my real data, the Array 3 that are created is still the same as the Array 1. So, I'm going to give more info about my stuff.
Both arrays are NSMutablArray that store dictionary objects. I'm actually using Parse.com, so the objects in both arrays are PFObject (which is just NSObject, if I'm not mistaken). I don't know how does this affect anything, but yeah, seems to not be working.
Here is a screenshot from the console when I try to step through the process.
Thanks for the help so far guys.
There's no need to go down the predicate route here, you know explicitly what you want to do, and can be expressed with simple, native APIs.
NSMutableArray *mArray3 = [NSMutableArray arrayWithArray:array1];
[mArray3 removeObjectsInArray:array2];
NSArray* array3 = [mArray3 copy];
An important thing to note:
removeObjectsInArray:
This method assumes that all elements in otherArray respond to hash and isEqual:.
For an object to be deemed equal, they need to response to hash and isEqual:, and for those values to match between two equal objects. A good article regarding equality can be read here.
If PFObject simply inherits from NSObject, then the equality checking will be very basic. It will simply check for equality by asking "Are these objects the same object, based on location in memory?". This probably explains why your dummy data works, but the real data does not.
You'll need to subclass PFObject to make it aware of the contents. This means you can override hash and isEqual: to provide a more reasonable statement of equality. For example, "Are these objects the same object, based on the value of the 'name' property". It's up to you to define what makes objects equal.
WDUK's answer is probably the way to go since it's simpler and requires only one new object (plus a copy of that). However, if you like discrete math, NSMutableSet allows you to perform set operations. That is, another (overly complicated, however, very descriptive) answer to your question is:
// convert arrays to sets.
// since array2 is always a subset of array1, we don't need to create a union set.
NSMutableSet *set1 = [NSMutableSet setWithArray:array1];
NSSet *set2 = [NSSet setWithArray:array2];
// find intersecting objects
NSMutableSet *intersection = [NSMutableSet setWithSet:set1];
[intersection intersectSet:set2];
// remove intersecting objects (result: your desired set)
[set1 minusSet:intersection];
NSArray *nonIntersectingObjects = [set1 allObjects];
As WDUK suggests, your problem is easily solved with an NSMutableArray. However, when similar, but more complex, problems arise, set operations might provide an simpler and more elegant solution.
If you want to do it using a predicate here's the way to do it:
NSArray* array1= #[#'A',#'B',#'C',#'D',#'E',#'F'];
NSArray* array2= #[#'B',#'E',#'F'];
NSPredicate* predicate= [NSPredicate predicateWithFormat: #"not(self in %#)",array2];
NSArray* array3=[array1 filteredArrayUsingPredicate: predicate];
SELF represents the evaluated object in the array. The IN operator can be used to check if any object is inside a collection, here is some reference: Predicate programming guide / aggregate operations
I have an NSMutableDictionary of custom objects of type "Fraction", which is composed of a numerator variable of type int, and a denominator variable also of type int. I am able to sort all of the values after they have been pulled from the NSMutableDictionary, and put into an NSArray. However, I have just discovered a new problem. Because my NSMutableDictionary is a collection of "Fraction" objects, it is very possible that some of these objects may be duplicates of one another, which means finding the respective "key" value from the original NSMutableDictionary will also cause problems. How do I overcome this? I have an NSMutableDictionary that contains NSStrings for keys, and custom "Fraction" objects for values. I have an NSArray that contains these custom "Fraction" objects, sorted from biggest, to smallest. The problem is that some of these objects may be the same (e.g. 1/2, 1/3, 1/3, 1/4). What I would like to know is how to pull each key for its respective "Fraction" object, despite the fact that there are duplicates?
Thanks in advance to all who reply.
To retrieve all keys for a particular object, use the allKeysForObject: method of NSDictionary.
I have an array (NSArray or NSMutableArray doesn't matter): SpecID of specific files IDs (109234, etc.). And I have a large array of all files IDs : FilesID.
I need to check whether FilesID contains all the elements of SpecID.
So the question what is the fastest and most efficient way of doing this except simple comparing all the elements to each other in a loop. May be there are some standard method or efficient algorithm?
You could use sets:
NSSet *specIDs = [NSSet setWithArray:specIDarray];
NSSet *fileIDs = [NSSet setWithArray:fileIDarray];
if ([specIDs isSubsetOfSet:fileIDs])
{
// Your file IDs contains every ID found in specIDarray
}
For this to work efficiently, the objects should ideally be NSNumber objects, or if they are custom objects, they should override both hash and isEqual:. The efficiency of sets depends mostly on having a good hash. The Foundation classes, e.g. NSNumber, NSString etc have good hashes.
Also, if you can, load your IDs directly into sets rather than converting them from arrays as this will be slightly more efficient, but otherwise the above is probably as simple as it would get. There may be specialised algorithms which would perform better but only explore those options if the above is too slow.