2012年2月17日 星期五

[iOS] Class 1: NSArray, NSMutableArray, NSDictionary, NSMutableDictionary

NSArray

1. Can contain different variable types.
2. Contents of array cannot be modified. (add, remove and sort)

Create NSArray
NSArray *bookList = [NSArray arrayWithObjects: @"iPhone4", @"iOS", @"MacX", nil];

Add an empty object
[NSNull null]

Retrieve NSArray
NSArray *bookList = [NSArray arrayWithObjects:@"Moby", @"Frank", @"Tom", nil];
for (int y=0; y < bookList.count, y++) {
    NSLog (@"Book Title is %@", [bookList objectAtIndex:y])
}
result:
Book Title is Moby
Book Title is Frank
Book Title is Tom


NSMutableArray
1. Similar to NSArray.
2. Contents of array can be modified. (add, remove and sort)

Create NSMutableArray
NSMutableArray *bookList = [NSArray arrayWithObjects:@"iPhone4", @"iOS", @"MacX", nil];

Add an object (append to the end of the bookList)
[bookList addObject:@"New book"];

Insert an object at an specific place "index".
[bookList insertObject:@"New book" atIndex:index];

Remove an object at "index".
[bookList removeObject:index];

Sort Array: in alphabetical order
[bookList sortUsingSelector:@selector(caseInsensitiveCompare:)];


NSDictionary

1. Cannot be modified. (add, remove and sort)

Create NSDictionary
NSDictionary *book = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"a", @"1",
                                      @"b", @"2",
                                      @"c", @"3",
                                      @"d", @"4",
                                      @"e", @"5",
                                       nil];

Retrieve Object
[book objectForKey: @"1"];

NSMutableDictionary
1. Can be modified. (add, remove and sort)

Create NSMutableDictionary
NSMutableDictionary *book = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  @"a", @"1",
                                                  @"b", @"2",
                                                  @"c", @"3",
                                                  @"d", @"4",
                                                  @"e", @"5",
                                                   nil];

Add an object
[book setObject: @"Value" forKey: @"KeyIndex"];


沒有留言:

張貼留言