1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
//数组的创建
NSArray *array1 = [NSArray arrayWithObject:@
"one"
];
NSArray *array2 = [NSArray arrayWithObjects:@
"one"
, @
"two"
, nil];
NSArray *array3 = [NSArray arrayWithArray:array2];
NSArray *array4 = [[NSArray alloc] initWithArray:array1];
NSLog(@
"%@, %@, %@, %@"
, array1, array2, array3, array4);
//输出:one
one,two
one,two
one
//数组中元素的访问与个数
int
count [array2 count];
//输出:count = 2
NSString *string1 = [array2 objectAtIndex:0];
//输出:string = one
//追加数组中的内容
NSArray *array5 = [array2 arrayByAddingObject:@
"end"
];
//输出:array5 = one,two,end
//数组->字符串
NSString *string2 = [array5 componentsJoinedByString:@
","
];
//输出:string2 = one,two,end
//判断数组中是否存在一个指定的对象
BOOL
isContain = [array5 containObject:@
"end"
];
//输出:isContain = 1
//根据指定的对象返回索引下标
NSInteger index = [array5 indexOfObject:@
"end"
];
//输出:index = 2
//返回数组中最后一个元素
NSString *lastObject = [array5 lastObject];
//输出:lastObject = end
/*****************可变数组*******************/
//创建一个空的数组
//NSMutableArray *mutableArray1 = [NSMutableArray array];
//NSMutableArray *mutableArray2 = [NSMutableArray arrayWithCapacity:5] //期望大小为5,实际可超过
NSMutableArray *mutableArray3 = [NSMutableArray arrayWithObjects:@
"one"
, @
"two"
, @
"end"
, @
"five"
, nil];
//追加一个内容
[mutableArray3 addObject:@
"four"
];
//输出:one, two, four
//根据索引插入一个内容
[mutableArray insertObject:@
"three"
atIndex:2];
//输出:one, two, three, four
//移除最后一个元素
[mutableArray removeLastObject];
//删除指定元素
[mutableArray removeObject:@
"end"
];
//删除指定下标元素
[mutableArray removeObjectAtIndex:3];
//删除指定数组内容
NSMutableArray *deleteArray = [NSMutableArray arrayWithObjects:@
"one"
, @
"two"
,nil];
[mutableArray removeObjectInArray:deleteArray];
//替换指定下标元素
[mutableArray replaceObjectAtIndex:2 withObject:
"six"
];
//移除所有对象
[mutableArray removeAllObejects];
/*************遍历数组*********************/
//常规遍历(性能较低)
NSArray *array = [NSArray arrayWithObjects:@
"a"
, @
"b"
, @
"c"
, nil];
int
length = [array count];
for
(
int
i=0; i<length; i++)
{
NSString *element = [array objectAtIndex:i];
NSLog(@
"%@"
, element);
}
//快速遍历(性能较高)
for
(NSString *string in array)
NSLog(@
"%@"
, string);
//当不确定数组的元素的类型时,可以选用id
for
(id string in array)
NSLog(@
"%@"
, string);
|