Wednesday, June 19, 2013

NSMutableDictionary setObject forKey example in Objective C (iOS).

NSMutableDictionary setObject forKey

Adds a given key-value pair to the dictionary.

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

Parameters of [NSMutableDictionary setObject forKey]
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 forKey example.
NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithDictionary:delegate.sharedData.dictFaves];
[dict setObject:@"test" forKey:@"4"];
delegate.sharedData.dictFaves = dict;
[dict release];

Example of [NSMutableDictionary setObject forKey].
- (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 forKey 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 forKey example article.