Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove object from NSDictionary

Hi i am having a NSdictionary in which i am adding a array with key "countries ". Now i take the value of this dictionary into array and sort the array in alpahbatical order .Now i want to add this array into my Dictionary (that is i want to update my dictionary with new sorted array and remove the old array from it )........ how to do this

My code is as follows

NSArray *countriesToLiveInArray = [NSArray arrayWithObjects:@"Iceland", @"Greenland", @"Switzerland", @"Norway", @"New Zealand", @"Greece", @"Italy", @"Ireland", nil];
NSDictionary *countriesToLiveInDict = [NSDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"];


NSArray *tmpary = [countriesToLiveInDict valueForKey:@"Countries"];
NSLog(@"ary value is  %@",ary);
NSArray *sortedArray = [tmpary sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSLog(@"sortedArray is %@",sortedArray);

Here i want to remove the countriesToLiveInArray and replace it with sortedArray with same key value i.e. Countries Thanks in advance..

like image 274
V.V Avatar asked Oct 07 '10 07:10

V.V


4 Answers

First you need to use a NSMutableDictionary and put this code :

[countriesToLiveInDict removeObjectForKey:@"Countries"];
[countriesToLiveInDict setObject:sortedArray forKey:@"Countries"];
like image 98
MathieuF Avatar answered Nov 08 '22 06:11

MathieuF


First of all make your NSDictionary to NSMutableDictionary & then write the following line of code

[countriesToLiveInDict removeObjectForKey:@"Countries"];

This will definitely resolve your issue.

like image 28
Atulkumar V. Jain Avatar answered Nov 08 '22 06:11

Atulkumar V. Jain


NSDictionary cannot remove anything, please use NSMutableDictionary, like this:

NSMutableDictionary *countriesToLiveInDict = [NSMutableDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"];
like image 1
Donald Avatar answered Nov 08 '22 05:11

Donald


for Swift 3 as @MathieuF answered it First you need to use a NSMutableDictionary and put this code :

countriesToLiveInDict.removeObject(forKey: "Countries")

i post my answer as i was search for same question and get inspired by @MathieuF

like image 1
Amr Angry Avatar answered Nov 08 '22 07:11

Amr Angry