NSDictionary: is order of iteration preserved? - ios

Say I want to access all objects in some NSDictionary object.
I want to iterate like this:
for (key in dict){}
Is it guaranteed that for each run the objects in the dictionary will be accessed in the same order?
PS. Let me explain my question more thoroughly: if I iterate dictionary once and access keys in some concrete order - will I have the same order on second iteration attempt?

Sorting of keys is not guaranteed because of the nature a key is placed inside the NSDictionary. But that is only the half answer. read on...
If we iterate thru the dict with a for (NSString* key in dict) loop or even more unspecific with for (id<NSCopying> key in dict) loop then we use actually NSEnumeration. Those kind of iterations are unpredictable to you. NSEnumeration and NSFastEnumeration do not iterate the dict with indexes. They go thru by addresses or hashes of keys, so to speak. Thats also a blurry answer that is not complete.
Keys inside a dict are unique compared to other keys in the same dict.
Which is the great thing and why you would use a NSDictionary or NSMutableDictionary instead of indexed NSArray or NSPointerArray or unspecific NSSet, and specially offered datatypes as NSOrderedSet, NSOrderedCollection. NSMapTable and NSHashTable tend to behave like NSDictionaries but they have a completely different way how they store the keys and how they iterate.
So what happens when you rewrite a keyed value in NSDictionary?
NSDictionary *dict = #{
#"A" : #(1234),
#"B" : #(4321)
}
NSMutableDictionary *mutabledict = [dict mutablecopy];
mutabledict[#"A"] = #(5678); //beware this only works on NSMutableDictionary.
dict = mutabledict;
here we exchange the value of the first declared key A.
mutabledict[#"A"] [key] is a getter subscript used to find the address of the keys value pair. Nothing is changed on the key itself. So the order of keys stays as it was the moment the unique key was copied in.
You need to be careful when you create a mutablecopy, because then whole pairs are copied. The outcome in sorting may be unpredictable as well.
Simple: But Accessing keys value does not change their memory layout.
But: NSDictionary are immutable, so the keys can not be changed once they are set. So you can say:
The keys are ordered in the order they where stored the first time. But you can't access the values stored in a guaranteed order when you don't know the order the keys:value pairs where placed and with this process its unique keys copied into the dict.
If you can't control the order the keys are set then the keys order is unknown to you, (respecting the question) not undefined. And NSEnumeration iteration gives you not a real picture of the order they are stored.
How to deal with that?
The easies way to get known ordered sorting of keys is by manually sorting all its keys like..
NSArray *sortedKeys = [dict.allKeys sortedArrayUsingSelector:#selector(compare:)];
which is giving you ascending order of keys and lets you iterate thru your dict with arrays indexes containing addresses to keys. like ..
for (unsigned int i=0; i<sortedKeys.count; i++) {
NSString* key = sortedKeys[i];
dict[ key ] = yourValue;
}
if keys are not of interest but the guaranteed sorting is more important to you, then you could convert the NSDictionary into a sorted NSArray without keys and access its indexes in a loop. With the obvious back-draw to have no keys unless you store them manually.
id notfoundmarker = #"empty";
NSArray *sortedkeys= [dict.allKeys sortedArrayUsingSelector:#selector(compare:)];
NSArray *oneForOneSorted = [dict objectsForKeys:sortedkeys notFoundMarker:notfoundmarker];
for (unsigned int i=0; i<oneForOneSorted.count; i++) {
id<NSObject> value = oneForOneSorted[i];
NSLog(#"%#", value);
};

My question was different: if I iterate dictionary once and access keys in some concrete order - will I have the same order on second iteration attempt?
Short Answer
In all probability yes
Longer Answer
How a dictionary is constructed internally is not specified, and there are multiple ways to represent dictionaries, all that is known is that key values must be hashable which implies hashing is used somehow.
It is also not know what algorithm a dictionary uses to provide the keys when enumerating them, and again for an particular possible representation there could be more than one enumeration algorithm possible.
So we have a lot of unknowns.
What do we know?
In the absence of threading, random number generation, and anything similar an Objective-C program is deterministic, a trait it has in common with C, Swift, Java, C# and a host of other languages.
NSDictionary is not thread-safe so its unlikely to use threading in its implementation.
And why would it use random numbers?
NSDictionary is also an immutable type so once constructed there is no obvious reason to re-order its internal storage in response to calls querying its contents.
So, in all probability, you will get the same key order on every enumeration.
Without the source though you can't be certain, you cannot prove the absence of something by black-box testing. Maybe the programmer decided that every millionth enumeration they'd throw a little randomness in – just for fun ;-) Is this likely? Maybe not (its probably a good way to get fired!), but it's not impossible.
If you ask out of curiosity, then good stay curious!
If however you want to rely on the order being deterministic for code correctness then sort the keys (into a peculiar order if you wish as long as its deterministic), the cost of doing so will in all probability be inconsequential.
HTH

The docs state that for the allKeys property the order of the elements in the array is not defined.
So you can just sort the keys array to ensure it's always sorted.

Each iteration will be in a random order because Swift dictionaries don't prioritize order. Arrays do, however, so you can sort the dictionary (by key or value) to produce an array of tuples, which in effect can be treated like a sorted dictionary.
let dictionary = ["k4": 3, "k2": 8, "k1": 6]
let sortedArrayOfTuples = dictionary.sorted(by: { $0.key < $1.key })
for entry in dictionary {
print(entry.key)
}
for entry in sortedArrayOfTuples {
print(entry.key)
}

Related

iOS Dictionary Response by added objects [duplicate]

I've run into the same problem as found in this question. However, I have a follow-up question. I seem to be in the same situation as the original asker: I have a plist with a hierarchy of dictionaries that define a configuration screen. These are not mutable and will stay the same throughout the application. Since the original discussion seems to focus on problems arising from mutating the dictionary, I must ask for comfirmation: is the order of a dictionary guaranteed the same as they are in the plist, i.e. as it is read (with initWithContentsOfFile)? Can I use allKeys on it in this case to get a correct-order array of keys if the dictionary never changes?
No, the keys are not likely to appear in the same order as your plist file. I can't look under the hood, but I would guess that the keys are ordered in whatever way that provides an efficient look-up. The documentation for allKeys says that the order of the elements in the array is not defined.
If you need an NSDictionary that maintains order, take a look at CHDataStructure's CHOrderedDictionary, which does exactly that. I use it all the time.
I would not assume that the keys will be in any kind of order because allKeys does not guarantee order.
Internally, NSDictionary uses a hash table.
From allKeys description:
The order of the elements in the array
is not defined.
If you want to display values in some order then get the keys, sort the keys array and then get the value for each key.
Nothing at all is guaranteed about order. It’s not even guaranteed that iterating over a dictionary twice will give you the keys in the same order.

Get index for value NSDictionary

I've got a value like so: #"2329300" and I've got a NSDictionary like so :{#"John Appleseed":[#"2329300",#"2342322",#"32i249"]}
How do I find the index of the key/value pair in the NSDictionary when I've only got a string value of the entire list that's known as the value. I'm assuming there's no duplicates in the dict.
I know that there's indexForObject on a NSArray but is there a similar thing for a dict?
I imagine it would look something like this:
[NSDictionary indexForValue:value]; // returns index number.
And even then the NSString doesn't match the value, so I'd need a workaround for that too.
You have a basic misunderstanding. Dictionaries are unordered collections. They do not have any particular order for their key/value pairs. You can't have indexes to the key/value pairs because that implies a fixed order.
Think of a dictionary as a bunch of kids milling around on a playground. You can call out a kid's name "Johnny, come here!" and fetch that kid (use a key to find an object) but what does order mean for kids that won't sit still?
You can create an array of the keys from a dictionary and sort that into a particular order (an alphabetical list of the kids on the playground) if that's what you want, or you can create an array of dictionaries, or an array of a custom data object that contains any arbitrary properties that you want.
EDIT:
For a table view, an array of dictionaries is probably a good choice. Each entry in the array contains a dictionary with all the settings for a cell in the dictionary. If you have a sectioned table view then you want an outer array for sections, containing inner arrays for the rows, and each entry in the inner array containing a dictionary.
I tend to prefer custom data objects to dictionaries though. (An object that just has properties for each setting I want.) That way the list of values and their types is crystal-clear and fairly self-documenting.

Get the opposite of intersection between array A and array B

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

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).

Loading NSDictionary from Plist as Listed

I'm using plist to store key-value lists. When the application needs that list, trying load list to a NSDictionary. Everything is well until here.
Here how I load the plist file:
NSString *myPlistFilePath = [[NSBundle mainBundle] pathForResource: #"cities" ofType: #"plist"];
cities = [NSDictionary dictionaryWithContentsOfFile: myPlistFilePath];
When we look at, cities is a NSDictionary. Then I pushed all list key values to a TableView, somehow its not listed as in plist file. Sorting random.
Is there way to figure out?
Thanks in advance.
An NSDictionary is not an ordered collection, that is, it does not guarantee to preserve order of the contents in any way. Its only function is to map from keys to values.
If you need the contents ordered, you can extract it from the NSDictionary using for example keysSortedByValueUsingSelector, which will extract the data in the collection, sort it by your criteria and store it in an (order preserving) NSArray.
Alternatively, consider using an Array in the root of the plist, containing an ordered list of city dictionaries. Then if you iterate over the array contained therein, they will be in the array order contained in the plist.
NSDictionary is not an ordered data structure.
Objects are listed based on allKeys functions and keys are listed in undefined way.
See the apple doc for allKeys function.
allKeys Returns a new array containing the dictionary’s keys.
(NSArray *)allKeys
Return Value A new array containing the dictionary’s keys, or an empty
array if the dictionary has no entries.
Discussion The order of the elements in the array is not defined.
If you wish to avoid using a selector to sort the keys, consider using an Array in the root of the plist. Then when you iterate over the array, the order is preserved. This runs o(n), which is shorter than the fastest possible sort algorithm by a factor of log(n)
eg:
cities{
list[
city{}
city{}
city{}
...
]
}

Resources