標籤:
- /*---------------------NSArray---------------------------*/
- //建立數組
- NSArray *array1 = [NSArray arrayWithObject:@"1"];
- NSArray *array2 = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
- NSArray *array3 = [NSArray arrayWithArray:array2];
- NSLog(@"array1 = %@",array1);
- NSLog(@"array2 = %@",array2);
- NSLog(@"array3 = %@",array3);
-
- //擷取數組內資料個數
- int count = [array2 count];
- NSLog(@"array2 size is %d",count);
-
- //訪問數組內的資料
- NSString *str1 = [array2 objectAtIndex:0];
- NSLog(@"array2 first content is %@",str1);
-
- //數組中插入資料 返回新的數組
- NSArray *array4 = [array3 arrayByAddingObject:@"4"];
- NSLog(@"array4 = %@",array4);
-
- //數組內的資料以制定字元串連
- NSString *str2 = [array4 componentsJoinedByString:@","];
- NSLog(@"str2 = %@",str2);
-
- //判斷數組中是否包含某對象
- BOOL b1 = [array4 containsObject:@"4"];
- BOOL b2 = [array4 containsObject:@"5"];
- NSLog(@"b1 = %d,b2 = %d",b1,b2);
-
- //取數組內製定對象的索引
- int index = [array4 indexOfObject:@"4"];
- NSLog(@"index = %d",index);
-
- NSString *str3 = [array4 lastObject];
- NSLog(@"array4 last object is %@",str3);
-
- /*-----------------------可變數組NSMutableArray-----------------------------------------*/
- //初始化數組 指定數組長度 但可變
- NSMutableArray *mArray1 = [NSMutableArray arrayWithCapacity:5];
-
- //向數組中添加元素
- [mArray1 addObject:@"aaaa"];
- [mArray1 addObject:@"cccc"];
- NSLog(@"mArray1 = %@",mArray1);
-
- //向指定位置插入元素
- [mArray1 insertObject:@"bbbb" atIndex:1];
- [mArray1 insertObject:@"dddd" atIndex:[mArray1 count]];
- [mArray1 insertObject:@"eeee" atIndex:[mArray1 count]];
- NSLog(@"mArray1 = %@",mArray1);
-
- //移除元素
- [mArray1 removeObject:@"eeee"];
- NSLog(@"mArray1 = %@",mArray1);
- [mArray1 removeObjectAtIndex:[mArray1 count]-1];
- NSLog(@"mArray1 = %@",mArray1);
- NSArray *array5 = [NSArray arrayWithObjects:@"bbbb",@"cccc", nil];
- [mArray1 removeObjectsInArray:array5];
- NSLog(@"mArray1 = %@",mArray1);
-
- //向數組插入入數組
- NSMutableArray *mArray2 = [NSMutableArray arrayWithObjects:@"aaaa",@"aaaa", nil];
- [mArray2 addObject:@"bbbb"];
- NSLog(@"mArray2 = %@",mArray2);
- [mArray2 addObjectsFromArray:array4];
- NSLog(@"mArray2 = %@",mArray2);
-
- //替換元素
- [mArray2 replaceObjectAtIndex:[mArray2 count]-1 withObject:@"5"];
- NSLog(@"mArray2 = %@",mArray2);
-
- //遍曆數組 常規方法:效能較低
- NSArray *array6 = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e", nil];
- int len = [array6 count];
- for (int i=0; i<len; i++) {
- NSString *value = [array6 objectAtIndex:i];
- NSLog(@"array6 %d content is %@",i,value);
- }
-
- //枚舉遍曆 相當於java中的增強for迴圈
- for (NSString *string in array6) {
- NSLog(@"array6 content is %@",string);
- }
-
- NSLog(@"-----------------------");
-
- //當不確定數組元素類型時
- for(id string in array6){
- NSLog(@"array6 content is %@",string);
- }
Objective-C中NSArray和NSMutableArray的基本用法