Objective-c之NSArray(NSMutableArray)
1、创建数组
NSArray *array = [[NSArray alloc]
initWithObjects:@"One",@"Two",@"Three",@"Four",nil];
2、数组所包含对象个数
[self.dataArray count]
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(inti = 0; i < [oldArray count]; i++)
{
obj= [[oldArray objectAtIndex:i] copy];
[newArrayaddObject: obj];
}
//
NSLog(@"newArray:%@",newArray);
[newArrayrelease];
6、深COPY
//NSMutableArray *newArray = [[NSMutableArrayalloc] 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);
[newArrayrelease];
7、快速枚举
//NSMutableArray *newArray = [[NSMutableArray alloc]init];
NSArray*oldArray = [NSArray arrayWithObjects:
@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];
NSLog(@"oldArray:%@",oldArray);
for(idobj in oldArray)
{
[newArrayaddObject: obj];
}
//
NSLog(@"newArray:%@",newArray);
[newArrayrelease];
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 = [NSMutableArrayarrayWithCapacity:20];
11、 在数组末尾添加对象
NSMutableArray *array = [NSMutableArrayarrayWithObjects:@"One",@"Two",@"Three",nil];
[array addObject:@"Four"];
NSLog(@"array:%@",array);
12、删除数组中指定索引处对象
NSMutableArray *array = [NSMutableArrayarrayWithObjects:@"One",@"Two",@"Three",nil];
[array removeObjectAtIndex:1];
NSLog(@"array:%@",array);