黑马程序员技术交流社区
标题: NSArray [打印本页]
作者: paradise6 时间: 2015-8-5 10:07
标题: NSArray
数组创建
NSArray *array1 = [NSArray arrayWithObject: @”rose”];
NSArray *array2 = [NSArray arrayWithObjects: @”jack”, @”jay”, nil];
NSArray *array3 = @[@”rain”, @”carlo”, @”Richard”];
数组访问
[array3 objectAtIndex: 1];
NSLog(@”%@”, array3[1]); // 编译器特性
数组长度
[array3 count]; // count是get方法,返回值为unsigned long,所以输出格式为%ld
array3.count;
数组遍历
循环结构
for(int i=0; i<array3.count; i++)
{
NSLog(@”array3[%d] = %@”, i, array3);
}
快速遍历
for(id obj in array)
{
NUInteger i = [array indexOfObject: obj];
NSLog(@”array3[%ld] = %@”, i, obj);
}
block遍历
[array3 enumerateObjectsUsingBlock:
^(id obj, NUInteger idx, bool *stop)
{
NSLog(@”array3[%ld] = %@”, idx, obj);
if (idx==1)
{
*stop = YES;
}
}];
补充:
字符串->数组
NSString *str = @”jack-rose-jim-jay-rain-richard”
NSArray *array = [str componentsSeperatedByString:@”-”]; // 字符串分解为数组
可变数组
创建
NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:@”rose”, @”jack”, nil];
添加元素
NSMutableArray *array2 = [array1 addObject:@”rain”];
Person *p = [[Person alloc] init];
NSMutableArray *array3 = [array2 addObject: p];
删除元素
NSMutableArray *array4 = [array3 deleteObject: @”rain”];
NSMutableArray *array5 = [array4 deleteObjectAtIndex:2];
NSMutableArray *array6 = [array5 removeAllObjects];
打印数组
NSLog(@”%@”, array4);
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |