Persisting NSCountedSet to NSUserDefaults - ios

I need to persist an NSCountedSet of custom objects to NSUserDefaults.
I think the problem is that -(id)objectForKey: for NSUserDefaults has a special consideration in the docs here:
Special Considerations
The returned object is immutable, even if the value you originally set was mutable.
Question
How would I go about persisting an NSCountedSet if (as I am currently assuming?) NSUserDefaults returns a non-mutable NSSet from -(id)objectForKey: when I need to retain the internal count metadata that NSCountedSet contains?

You can't write an NSCountedSet to user defaults. Only arrays, dictionaries, strings, numbers, date and data.
You could create a dictionary matching the NSCountedSet, with the set elements as keys and the counts converted to NSNumber as values. And of course when you read the dictionary, convert it to a counted set. Just a few lines of code.
Alternatively, convert to an array with values duplicated depending on their count. If the counted set contains "Hello" with a count of 3, add it to the array three times.

Related

isEqualToArray or isEqualToDictionary how deep can it compare?

Ohkk So I have many scenarios here.
case:1
A NSArray of dictionaries with a key as type NSString and value also of type NSString.In this case if I change one value in the NSdictionary on the array and try comparing old array with new one it works. isEqualToArray returns false
case:2
A NSArray of dictionaries with a key type as NSString and value type of some model object with attributes like name,address,DOB . So if I change one value in the model object like name and insert in the dictionary with same key. And compare the arrays with old one still works. isEqualToArray returns false
Now this can go on .What if I have a NSArray in my model object which of again a primitive type of some model.What will happen?? Does isEqualToArray compares almost everything in the values of the objects like deep-serializing compare or it has to stop somewhere??
When you compare arrays, the NSArray isEqual: method first checks that both arrays have the same number of elements (otherwise, they are obviously not the same), and then it goes through all the elements one by one and compares them in turn using the isEqual: method. So if your array contains other arrays, or dictionaries, or other objects, then arrays are again compared as just described, dictionaries will be compared as I will describe, and other objects are compared by sending isEqual.
When you compare dictionaries, the NSDictionary isEqual: method first checks both dictionaries have the same number of key/value pairs. Then it takes the first key of the first dictionary, and that key must be present in the second dictionary, and the objects must be the same. Then the second key, the third key and so on.
It all works as long as each class involved has a proper implementation of the isEqual: method. It really has nothing to do with isEqualToArray:. All that does is call isEqual: on each object in the two arrays. So it depends on those objects having a valid isEqual: method (and hash method).
As long as your model object's isEqual: method properly compares each of its properties, you will get the expected result.

What is the most reliable and fastest type or data structure to store data using Objective C?

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

What is a good way to store a persistent array?

I have an NSMutableArray of objects that I would like to persist between user sessions. Each object has an NSInteger property, and I would like to be able to access all of the objects for calculations using that property (averages, mins, maxes, etc.)
Would it be better to store that array into a Core Data database or just store my objects individually into the database?
EDIT: The array should hold no more than 1,000 items.
Depends on the size. If it's simple just archive the array to a file
Edited to add
If all you want to persist is an array you don't need to use the archiver methods, you can do it directly.
Imagine you have a file URL in your app's Documents directory called persistentURL which you want to use to save and read your array from.
All you need to do to persist the array is:
[yourArray writeToURL:persistentURL atomically:YES];
And when you want to read the data back into an array it's as simple as:
yourArray = [NSArray arrayWithContentsOfURL:persistentURL];
You can use this method here because the array contains only NSNumbers which are property list objects (i.e. objects that can be put directly into a plist).
NSArray and NSMutableArray can't contain integers directly. It has to contain NSNumber objects.
Anyway, I'd just use NSCoding. Try the methods archiveRootObject:toFile: (which writes directly to a file) or archivedDataWithRootObject (which converts the content to a byte-stream in NSData).
For <=1000 items it should be fast enough.
If you're reading and writing the array enough, you might want to consider using a malloc'ed C array of "long"s, and saving that as bytes to a file. That would be faster, and you could read/write values to your C array easily, instead of having to do object replacement. On the other hand resizing the array or inserting values is a pain with a C array, and you also have to be aware of data size and byte ordering issues if you will ever transfer this data between devices.
Edit: I just wrote a little test, and writing an NSArray of 1,000 NSNumbers to a file with archiveRootObject:toFile: takes about 0.0038 seconds on on old iPhone 4 I have around for testing. That's the slowest machine that supports iOS 7, and it's 3.8 THOUSANDTHS of a second, to write 1,000 items. So writing an array of 10,000 items should take 3.8 hundredths of a second or less.
Unless you are reading and writing this array many times a second in a loop, using archiveRootObject:toFile: is plenty fast enough.
Personally, I would use the following to store that array:
[[NSUserDefaults standardUserDefaults] setObject:myArray ForKey:#"myArray"]
and retrieve it anywhere in the app:
NSMutableArray *myArray = [[[NSUserDefaults standardUserDefaults] objectForKey:#"myArray"] mutableCopy];
That seems to me to be the easiest way to persist that data. You can store the mutable array in NSUser defaults, and I believe you'll need to create a mutable copy of it when you retrieve it later on to be able to continue to make changes to it.

Availability of bidictionary structure?

I'm facing a case in my application where I need a bidirectional dictionary data structure, that means a kind of NSDictionary where your can retrieve a key with a value and a value with a key (all values and keys are unique).
Is there such a kind of data structure in C / ObjectiveC ?
You can do it with a NSDictionary:
allKeysForObject: Returns a new array containing the keys
corresponding to all occurrences of a given object in the dictionary.
(NSArray *)allKeysForObject:(id)anObject Parameters anObject The value to look for in the dictionary. Return Value A new array
containing the keys corresponding to all occurrences of anObject in
the dictionary. If no object matching anObject is found, returns an
empty array.
Discussion Each object in the dictionary is sent an isEqual: message
to determine if it’s equal to anObject.
And:
objectForKey: Returns the value associated with a given key.
(id)objectForKey:(id)aKey Parameters aKey The key for which to return the corresponding value. Return Value The value associated with
aKey, or nil if no value is associated with aKey.
Literally, the answer is No.
As a workaround you may create a helper class which manages two dictionaries.
Another approach is to create a thin wrapper around C++ container which implement this: boost's Bimap.
When using ARC and Objective-C objects as values or keys in C++ containers, they will handle NSObjects quite nicely. That is, they take care of memory management as you would expect - and you even get "exception safety" for free. Additionally, C++ standard containers are also a tad faster, use less memory, and provide more options to optimize (e.g. custom allocators).

Sorting an NSMutableDictionary of custom objects whose values may contain duplicates

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.

Resources