標籤:
Objective-C的數組比C++,Java的數組強大在於,NSArray儲存的對象可以是不同的對象。但只能儲存對象,int ,char,double等基礎資料型別 (Elementary Data Type)不能直接儲存,需要通過轉換成對象才能加入數組。
1、NSArray 不可變數組
[array count] : 數組的長度。
[array objectAtIndex 0]: 傳入數組腳標的id 得到資料對象。
[arrayWithObjects; ...] :向數組對象初始化賦值。這裡可以寫任意對象的指標,結尾必須使用nil。
1.1、建立數組
1、建立數組
NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil]; |
|
2、數組所包含對象個數
3、擷取指定索引處的對象
[self.dataArray objectAtIndex:2] |
|
4、從一個數組拷貝資料到另一數組(可變數級)
//arrayWithArray: //NSArray *array1 = [[NSArray alloc] init]; NSMutableArray *MutableArray = [[NSMutableArray alloc] init]; NSArray *array = [NSArray arrayWithObjects: @"a",@"b",@"c",nil]; NSLog(@"array:%@",array); MutableArray = [NSMutableArray arrayWithArray:array]; NSLog(@"MutableArray:%@",MutableArray);
array1 = [NSArray arrayWithArray:array]; NSLog(@"array1:%@",array1); |
|
5、COPY
NSMutableArray *newArray = [[NSMutableArray alloc] init]; NSArray *oldArray = [NSArray arrayWithObjects: @"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];
NSLog(@"oldArray:%@",oldArray); for(int i = 0; i < [oldArray count]; i++) { obj = [[oldArray objectAtIndex:i] copy]; [newArray addObject: obj]; } // NSLog(@"newArray:%@", newArray); [newArray release]; |
|
6、深COPY
//NSMutableArray *newArray = [[NSMutableArray alloc] init]; NSArray *oldArray = [NSArray arrayWithObjects: @"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil]; NSLog(@"oldArray:%@",oldArray); newArray = (NSMutableArray*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef)oldArray, kCFPropertyListMutableContainers); NSLog(@"newArray:%@", newArray); [newArray release]; |
|
7、快速枚舉
//NSMutableArray *newArray = [[NSMutableArray alloc] init]; NSArray *oldArray = [NSArray arrayWithObjects: @"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil]; NSLog(@"oldArray:%@",oldArray);
for(id obj in oldArray) { [newArray addObject: obj]; } // NSLog(@"newArray:%@", newArray); [newArray release]; |
|
8、切分數組
NSString *string = [[NSString alloc] initWithString:@"One,Two,Three,Four"]; NSLog(@"string:%@",string); NSArray *array = [string componentsSeparatedByString:@","]; NSLog(@"array:%@",array); [string release]; |
|
9、從數組合并元素到字串
NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil]; NSString *string = [array componentsJoinedByString:@","]; NSLog(@"string:%@",string); |
|
10、 給數組分配容量
array = [NSMutableArray arrayWithCapacity:20]; |
|
11、 在數組末尾添加對象
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil]; [array addObject:@"Four"]; NSLog(@"array:%@",array); |
|
12、刪除數組中指定索引處對象
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil]; [array removeObjectAtIndex:1]; NSLog(@"array:%@",array); |
Objective-C文法之NSArray和NSMutableArr