looping through an NSMutableDictionary - objective-c

How do I loop through all objects in a NSMutableDictionary regardless of the keys?

A standard way would look like this
for(id key in myDict) {
id value = [myDict objectForKey:key];
[value doStuff];
}

you can use
[myDict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];
if your target OS supports blocks.

You can use [dict allValues] to get an NSArray of your values. Be aware that it doesn't guarantee any order between calls.

For simple loop, fast enumeration is a bit faster than block-based loop
It's easier to do concurrent or reverse enumeration with block-based enumeration than with fast enumeration
When looping with NSDictionary you can get key and value in one hit with a block-based enumerator, whereas with fast enumeration you have to use the key to retrieve the value in a separate message send
in fast enumeration
for(id key in myDictionary) {
id value = [myDictionary objectForKey:key];
// do something with key and obj
}
in Blocks :
[myDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];

You don't need to assign value to a variable. You can access it directly with myDict[key].
for(id key in myDict) {
NSLog(#"Key:%# Value:%#", key, myDict[key]);
}

Another way is to use the Dicts Enumerator. Here is some sample code from Apple:
NSEnumerator *enumerator = [myDictionary objectEnumerator];
id value;
while ((value = [enumerator nextObject])) {
/* code that acts on the dictionary’s values */
}

Related

NSMutableDictionary keyEnumerator or NSArray?

I have an NSMutableDictionary with a structure like:
Main Dictionary > Unknown Dictionary > Dictionaries 1,2,4,5,6...
My question is what is the best way to retrieve the Unknown Dictionary key and set it as a variable? This is what I've tried:
NSEnumerator *enumerator = [myMutableDict keyEnumerator];
id aKey = nil;
while ( (aKey = [enumerator nextObject]) != nil) {
id value = [myMutableDict objectForKey:aKey]; // changed to `aKey`
NSLog(#"%#: %#", aKey, value); // tip via rmaddy
}
What goes into objectForKey: if you don't know the name of the object in the key?
The other thought I had was to populate an NSArray, then pulling each of the keys out somehow.
for (NSString *object in myMutableDict)
myArray = [myArray arrayByAddingObject:MainDict];
}
If anyone can suggest a better way to get the object (unknown) from an NSMutableDictionary I'm interested to learn.
You can enumerate dictionaries like this:
NSDictionary * someDictionary = ... however you set your dictionary;
[someDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"Key: %#", key);
NSLog(#"Object: %#", obj);
}];
and set:
*stop = YES;
when you find the object you're looking for.
I'm not entirely sure if I understand your question correctly. I assume you have a "main" dictionary with exactly one (unknown) key that maps to another dictionary, which you want to retrieve. This would be a simple and concise way to do this:
NSDictionary *unknownDictionary = mainDictionary[mainDictionary.allKeys.firstObject];
(Yes, some people won't like the dot syntax here, but I find it easier to read in this case. You might also want to add some error checking, for the case that mainDictionary is empty etc.)

Search String in NSDictionary store in NSMutableArray

I am trying to search a String in NSDictionary stored in NSMutableArray
for (int k = 0; k < [onlyActiveArr count]; k++) {
NSString *localID = [onlyActiveArr objectAtIndex:k];
NSLog(#"%#",localID);
int localIndex = [onlyActiveArr indexOfObject:localActiveCallID];
NSLog(#"%d",localIndex);
for (NSDictionary *dict in self.SummaryArr) {
NSLog(#"%#",[dict objectForKey:#"ActiveID"]);
if (![[dict objectForKey:#"ActiveID"] isEqualToString:localID]) {
NSLog(#"found such a key, e.g. %#",localID);
}
}
}
But I am getting
NSLog(#"found such a key, e.g. %#",localActiveCallID);
when the ID is still there in SummaryArr, I am checking if localID retrieved from onlyActiveArr is not present in dictionary.
Please suggest me how to overcome my problem.
You cannot make a decision that a key is not present until you finish processing the entire dictionary. Make a boolean variable initially set to NO, and change it to YES if you find an item in the dictionary, like this:
BOOL found = NO;
for (NSDictionary *dict in self.SummaryArr) {
NSLog(#"%#",[dict objectForKey:#"ActiveID"]);
found = [[dict objectForKey:#"ActiveID"] isEqualToString:localID];
if (found) break;
}
if (!found) {
NSLog(#"found such a key, e.g. %#",localID);
}
If you like predicates, then you can use the fact that accessing an inexistent key in a dictionary produces a nil value and make a predicate that filters out those dictionaries that have nil for your key.
If the count of the result is larger than zero, your key is somewhere in the array. It won't tell you where, though.
A snippet to show the idea:
NSPredicate *keyPred = [NSPredicate predicateWithFormat: #"NOT ActiveID == nil"];
BOOL found = [[self.SummaryArr filteredArrayUsingPredicate: keyPred] count] > 0;
I don't know how the performance stacks up, so if your data set is large you may want to check that the execution time is within your limits.

Count equal objects in NSArray

I've been trying to figure out a way of checking how many of a certain object are in an NSArray.
I've looked through the docs and I'm pretty sure there is no premade method for this. Also I can't find anything here on SO.
Do anybody know about a good way to do this? Because I seriously can't come up with anything.
In this specific case I have an array with strings (most cases several of each) and I want to count how many strings in the array that matches to whatever I ask for.
If this is a primary use of the data structure and order doesn't matter, consider switching to an NSCountedSet which is specifically for solving this problem efficiently.
If you need an ordered collection, and you don't have a huge set of objects, than the fast enumeration answers are the best approach.
If you want to know where the objects are, then use indexesOfObjectsPassingTest:.
If you have a huge number of object, I would look at indexesOfObjectsWithOptions:passingTest: with the NSEnumerationConcurrent option. This will allow you to search the array on multiple cores. (This is only possibly faster on a multi-core device, and even then is probably only faster if you have a very large collection. You should absolutely test before assuming that concurrent will be faster.) Even if you just need the final count, it may be faster for certain data sets to use this method and then use count on the final index set.
There actually is a method for this: - (NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger index, BOOL *stop) {
return [obj isEqualTo:myOtherObject];
}];
Sounds like a case for NSCountedSet, which does what you are after with its initWithArray: initializer:
// Example array of strings
NSArray *array = [NSArray arrayWithObjects:
#"Joe", #"Jane", #"Peter", #"Paul",
#"Joe", #"Peter", #"Paul",
#"Joe",
#"Jane", #"Peter",
nil];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray: array];
// for-in will let you loop over the counted set
for (NSString *str in countedSet) {
NSLog(#"Count of %#: %ld", str, (long)[countedSet countForObject:str]);
}
One approach would be to iterate and check.
- (int)repeatsOf:(NSString *)repeater inArray:(NSArray *)array {
int count = 0;
for (NSString *item in array) {
if ([item isEqualToString:repeater]) {
count++;
}
}
return count;
}
You could try a simple loop. Suppose needle is your reference string and array is your NSArray of strings:
unsigned int n = 0;
for (NSString * str in array)
{
if ([needle isEqualToString:str])
{
++n;
}
}
Now n holds the count of strings in equal to needle.
You could define a function like this:
- (int)countStringsThatMatch:(NSString*)match inArray:(NSArray*)array
{
int matches = 0;
for (id string in array) {
if ([string isEqualToString:match]) {
matches++;
}
}
return matches;
}
And then use it like:
int count = [self countStringsThatMatch:#"someString" inArray:someArray];
- (NSUInteger) objectCountInArray:(NSArray *)array
matchingString:(NSString *)stringToMatch {
NSUInteger count = 0;
for (NSString *string in array) {
count += [string isEqualToString:stringToMatch] ? 1 : 0;
}
return count;
}
You can try to expand this to use a block that gets an object and returns a BOOL. Then you can use it to compare an array of whatever you want.

How to remove elements in NSMutableArray or NSMutableDictionary during enumeration?

I am using block based enumeration similar to the following code:
[[[rows objectForKey:self.company.coaTypeCode] objectForKey:statementType]
enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id coaItem, NSUInteger idx, BOOL *stop) {
// block code here
}]
I would like to remove some of the objects during the enumeration process depending on the their object values.
How could I do this? I know that manipulating an mutable array or dictionary (NSMutableArray or NSMutableDictionary) during enumeration is usually not possible.
What would be the best way to implement this?
Thank you!
Since you can't remove objects from an array or dictionary during enumeration, you'll have to accumulate the items you want to delete, and then delete them all after the enumeration.
If you're dealing with an array, you can just accumulate the indices.:
NSMutableIndexSet *indexesToDelete = [NSMutableIndexSet indexSet];
NSUInteger currentIndex = 0;
for (id obj in yourArray) {
//do stuff with obj
if (shouldBeDeleted(obj)) {
[indexesToDelete addIndex:currentIndex];
}
currentIndex++;
}
[yourArray removeObjectsAtIndexes:indexesToDelete];
Since the order of the keys in an NSDictionary is undefined, for an NSMutableDictionary you'll have to accumulate keys instead:
NSMutableArray *keysToDelete = [NSMutableArray array];
for (id obj in [yourDictionary keyEnumerator]) {
//do stuff with obj
if (shouldBeDeleted(obj)) {
[keysToDelete addObject:obj];
}
}
[yourDictionary removeObjectsForKeys:keysToDelete];
It's the same thing if you're enumerating with a block. Declare the enumerator in the same scope where you declare the block and it will be retained and just work.
Also worth looking at this question from 3 years ago: Best way to remove from NSMutableArray while iterating?.
Whether you build up an index set during enumeration, or modify the array itself during enumeration, you will have to give up NSEnumerationConcurrent, because most Cocoa objects cannot safely be modified simultaneously from multiple threads.
Anyway, the simplest (but maybe not most efficient) approach is to just enumerate a copy of the container.
For an array, you can enumerate a copy in reverse. I assume that as each item is being enumerated, you may decide to remove that item, but not other items previously enumerated or yet to be enumerated.
NSMutableArray *array = [[rows objectForKey:self.company.coaTypeCode] objectForKey:statementType];
[[array copy] enumerateObjectsWithOptions: NSEnumerationReverse
usingBlock:^(id coaItem, NSUInteger idx, BOOL *stop) {
if ([self objectIsTooUglyToExist:coaItem])
[array removeObjectAtIndex:idx];
}]
You have to enumerate the array in reverse to avoid changing the not-yet-enumerated part of the array.
For a dictionary, you can just enumerate a copy with no special options:
NSMutableDictionary *dictionary = someDictionary;
[[dictionary copy] enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([self object:obj isTooUglyToExistAtKey:key])
[dictionary removeObjectForKey:key];
}];
Another option, with an array, is to use a conventional for loop, with the array's count as the limit. Then one needs to be cognizant of whether an element is removed from a location <= the index (in which case the index should be decremented) or > than the index (in which case the index is left unmodified other than the for statement's increment).
For a dictionary you can first create an array with allKeys, and then iterate through the array. In this case no fiddling with index values is required.

NSDictionaray dictionaryWithObjectsAndKeys adding NULL value

I want to create a NSDictionary with +[NSDictionary dictionaryWithObjectsAndKeys:]. One of my keys has a string but the string can sometimes be nil. If the string is nil, any other value key pairs I put afterward will be ignored because the list is prematurely terminated. What is the standard way to deal with the possibility that there might be a value with nil in a NSDictionary?
You need to check if the string is null. If it is, add [NSNull null] instead of your string.
Creating NSDictionary objects can be combersome if you have many objects, that if they are nil, should not be included in the dictionary.
To me NSNull is as big a problem as it is the solution. When creating NSDictionary objects for usage in other objects, you can go two ways when dealing with nil values. Either you add NSNull objects to your dictionary - and then check for NSNull values when reading the values. This makes pretty code at the point of creation, but it becomes messy when reading out the values. Ex. should you check all keys in the dictionary, or are some garanteed to be not nil? And if an NSNull value is not filtered out it is bound to make exceptions when trying to send the object messages.
The second way is to just not add NSNull values to the dictionary. This is convinient when reading the NSDictionary, as the [someDictionary objectForKey:someKey] simply returns nil when the key is not set. This approach makes it pretty this easy when reading the values, but it really is bound to be messy code on creation. Ex. Creating a NSMutableDictionary, checking for nil before adding values, and finally returning an immutable copy?
Solution
To me the solution has been to create two categories, which in essense makes it easy for both the creating and the reading ends.
When creating the NSDictionary, you simply wrap you possible-nil values like this
[NSDictionary dictionaryWithObjectsAndKeysIngoringNull:
[NSNull nullWhenNil:val1], #"value1",
[NSNull nullWhenNil:val2], #"value2",
...
nil];
This code is almost as simple as approach number one, but it makes it substantially easier when reading out the values.
The categories is as follows (works in both ARC enabled and non-ARC code):
NSDictionary addition:
#implementation NSDictionary (NullAddition)
+ (id)dictionaryWithObjectsAndKeysIngnoringNull:(id)firstObject, ... {
NSMutableArray* objects = [NSMutableArray array];
NSMutableArray* keys = [NSMutableArray array];
va_list args;
va_start(args, firstObject);
for (id object = firstObject; object; object = va_arg(args, id)) {
id key = va_arg(args, id);
if (!key)
break;
if (![object isKindOfClass:[NSNull class]]) {
[objects addObject:object];
[keys addObject:key];
}
}
va_end(args);
return [self dictionaryWithObjects:objects forKeys:keys];
}
#end
NSNull addition
#implementation NSNull (NullAddition)
+ (id)nullWhenNil:(id)obj {
return (obj ? obj : [self null]);
}
#end
Good luck!
Attempting to insert data (key or value) into an NSDictionary will result in a Run Time Error. Therefore, you do not have to deal with null data in the dictionary.
'-[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: Test)'
and
'-[__NSCFDictionary setObject:forKey:]: attempt to insert nil key'
However, this means you are responsible for checking the validity of the data before putting it into the dictionary to prevent crashes.
I encounter a similar problem and google take me here. I need to add some kv into the dictionary whose value may be nil. Inspired by Trenskow's answer, I modify that function to support insert nil value, not terminate as before.
#define KV_END NSNull.null
NSDictionary *NSDictionaryOfKV(id firstKey, ...) {
__auto_type dict = [NSMutableDictionary dictionary];
va_list args;
va_start(args, firstKey);
for (id key = firstKey; key != NSNull.null; key = va_arg(args, id)) {
id obj = va_arg(args, id);
if (obj == NSNull.null) {
break;
}
if (key) {
dict[key] = obj;
}
}
va_end(args);
return dict.copy;
}
__auto_type value2 = nil;
__auto_type dict = NSDictionaryOfKV(key1, value1, key2, value2, key3, value3, KV_END);
You will got
{
key1: value1,
key3: value3
}
You can change the KV_END to anything you want.
This make sense when your value is a variable, you can use it as-is, don't need to wrap it or like value ?: NSNull.null.