James (MrGeckosMedia.com), joined by, Eduardo (MegaEduX.com), and John (@ZimiPoder), shows how Dictionaries, Arrays and Property Lists works in Cocoa.
12:40
Example code from episode.
#import
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Array");
NSArray *array = [NSArray arrayWithObjects:@"Orange", @"Apple", @"Banana", nil];
for (int i=0; i<[array count]; i++) {
NSLog(@"%@", [array objectAtIndex:i]);
}
NSLog(@"Sorting Array");
array = [array sortedArrayUsingSelector:@selector(compare:)];
for (int i=0; i<[array count]; i++) {
NSLog(@"%@", [array objectAtIndex:i]);
}
NSLog(@"Saving Property List");
[array writeToFile:[@"~/Desktop/array.plist" stringByExpandingTildeInPath] atomically:YES];
NSLog(@"Mutable Array");
NSMutableArray *mutableArray = [NSMutableArray array];
[mutableArray addObject:@"Apples"];
[mutableArray addObject:@"Oranges"];
[mutableArray addObject:@"Bananas"];
for (int i=0; i<[mutableArray count]; i++) {
NSLog(@"%@", [mutableArray objectAtIndex:i]);
}
NSLog(@"Removing object Oranges");
[mutableArray removeObjectAtIndex:1];
for (int i=0; i<[mutableArray count]; i++) {
NSLog(@"%@", [mutableArray objectAtIndex:i]);
}
NSLog(@"Dictionary");
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Oranges", @"Name", @"Fruit", @"Type", [NSNumber numberWithBool:YES], @"Seeds", nil];
NSLog(@"Adding %@ with name %@", [dictionary objectForKey:@"Type"], [dictionary objectForKey:@"Name"]);
[mutableArray insertObject:dictionary atIndex:1];
for (int i=0; i<[mutableArray count]; i++) {
NSLog(@"%@", [mutableArray objectAtIndex:i]);
}
NSLog(@"Saving Property List using NSPropertyListSerialization");
NSData *xmlData = [NSPropertyListSerialization dataFromPropertyList:mutableArray format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
[xmlData writeToFile:[@"~/Desktop/mutableArray.plist" stringByExpandingTildeInPath] atomically:YES];
NSLog(@"Mutable Dictionary");
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionary];
[mutableDictionary setObject:@"Salad" forKey:@"Name"];
[mutableDictionary setObject:@"Veggie" forKey:@"Type"];
[mutableDictionary setObject:[NSDate date] forKey:@"Time"];
[mutableDictionary setObject:[NSNumber numberWithBool:NO] forKey:@"Seeds"];
NSLog(@"Adding %@ with name %@", [mutableDictionary objectForKey:@"Type"], [mutableDictionary objectForKey:@"Name"]);
[mutableArray insertObject:mutableDictionary atIndex:0];
for (int i=0; i<[mutableArray count]; i++) {
NSLog(@"%@", [mutableArray objectAtIndex:i]);
}
NSLog(@"Saving Binary Property List");
NSData *binaryData = [NSPropertyListSerialization dataFromPropertyList:mutableArray format:NSPropertyListBinaryFormat_v1_0 errorDescription:nil];
[binaryData writeToFile:[@"~/Desktop/bina ry.plist" stringByExpandingTildeInPath] atomically:YES];
[pool drain];
return 0;
}
Keynote used in this Episode
Keynote in PDF Format