Reputation: 6114
I want to add all the keys from the dictionary to the array. This is what I am doing right now.As code below:
for (NSString * akey in _groups ) {
NSLog(@"%@",akey);
[_groupArray addObject:akey];
NSLog(@"%@",_groupArray);
}
The log is showing Null for _groupArray. I even tried using insertObjectAtIndex
even that does not work.Not sure what I am doing wrong and yes I am getting the keys in the dictionary (_groups) nothing wrong with that.
Upvotes: 0
Views: 2180
Reputation: 27506
You should initialize the array before starting to add values to it. Otherwise it is initially nil
and will remain nil
.
You can use allKeys
to get all the keys of the array. But since _groupArray
is an NSMutableArray
, you have to do that like this:
_groupArray = [NSMutableArray arrayWithArray:[_groups allKeys]];
Or:
_groupArray = [[_groups allKeys] mutableCopy];
Upvotes: 2
Reputation: 7072
Have you checked you've alloc'd and init'd your mutable array. Unless there's already stuff in it that you're adding to - and even then - consider using the NSDictiomary allKeys method rather than iterating through the dictionary.
From the docs
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.
Upvotes: 0
Reputation: 14068
If _groupsArray is new or empty anyway then you can use
_gropusArray = [NSMutableArray arrayWithArray:[dict allKeys]];
That should release you from the compiler warning.
If _groupsArray was not empty before and you need to addValues then go for:
[_groupsArray addObjectsFromArray:[dict allKeys]];
Upvotes: 1
Reputation: 12405
this is how you should do it....
_groupsArray=[dict allKeys];
don't forget to allocate memory to your _groupsArray.. :)
Upvotes: 0