Wednesday, June 19, 2013

NSMutableDictionary setObject example in Objective C (iOS).

NSMutableDictionary setObject

Adds a given key-value pair to the dictionary.

- (void)setObject:(id)anObject forKey:(id < NSCopying >)aKey

Parameters of [NSMutableDictionary setObject]
The value for aKey. A strong reference to the object is maintained by the dictionary. Raises an NSInvalidArgumentException if anObject is nil. If you need to represent a nil value in the dictionary, use NSNull.
The key for value. The key is copied (using copyWithZone:; keys must conform to the NSCopying protocol). Raises an NSInvalidArgumentException if aKey is nil. If aKey already exists in the dictionary anObject takes its place.

NSMutableDictionary setObject example.
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:delegate.sharedData.dictFaves];
[dict setObject:@"test" forKey:@"4"];
delegate.sharedData.dictFaves = dict;
[dict release];

Example of [NSMutableDictionary setObject].
- (BOOL)addStudent:(Student *)newStudent
    NSLog(@"adding new student");
    if (studentStore == nil) {
        studentStore = [[NSMutableDictionary alloc] init];
    [studentStore setObject:newStudent forKey:newStudent.adminNo];
    return YES;

NSMutableDictionary setObject example.
//NSMutableDictionary myDictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];

NSNumber *value = [myDictionary objectForKey:myWord];

if (value)
    NSNumber *nextValue = [NSNumber numberWithInt:[value intValue] + 1];
    [myDictionary setObject:nextValue  forKey:myWord];
    [myDictionary setObject:[NSNumber numberWithInt:1] forKey:myWord]

End of NSMutableDictionary setObject example article.