34

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

P.J.Radadiya
  • 1,493
  • 1
  • 12
  • 21
V.V
  • 3,082
  • 7
  • 49
  • 83

4 Answers4

73

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

[countriesToLiveInDict removeObjectForKey:@"Countries"];
[countriesToLiveInDict setObject:sortedArray forKey:@"Countries"];
john.k.doe
  • 7,533
  • 2
  • 37
  • 64
MathieuF
  • 3,130
  • 5
  • 31
  • 34
  • 21
    You don't need to remove the previous object for the key. -setObject:forKey: automatically releases the previous object, if called on a kety that already exists. – JeremyP Oct 07 '10 at 08:51
6

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

[countriesToLiveInDict removeObjectForKey:@"Countries"];

This will definitely resolve your issue.

Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
  • 2
    Is setting the `countriesToLiveInDict =` necessary? – DCurro Mar 08 '16 at 14:59
  • Don't do this, the documentation states `-[NSMutableDictionary removeObjectForKey:]` returns `void`. See: [- (void)removeObjectForKey:(KeyType)aKey](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableDictionary_Class/#//apple_ref/occ/instm/NSMutableDictionary/removeObjectForKey:) – Tyr0 Apr 28 '16 at 23:56
1

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

Amr Angry
  • 3,711
  • 1
  • 45
  • 37
1

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

NSMutableDictionary *countriesToLiveInDict = [NSMutableDictionary dictionaryWithObject:countriesToLiveInArray forKey:@"Countries"];
eeerahul
  • 1,629
  • 4
  • 27
  • 38
Donald
  • 321
  • 1
  • 2
  • 10