标签:
OC中的数组:
OC中的数组和它的字符串有很多相似之处。也分为可变和不可变。
NSArray:不可变数组,一经初始化,便不能再更改;
NSMutableArray:可变数组,它其实是继承于NSArray,所以NSArray的方法它都可以用,只不过又拓展了些数组自己操作的方法。
OC数组的初始化:
//NSArray:不可变数组 //NSArray的实例化方法: //对象方法: NSArray * arr1 = [[NSArray alloc]initWithObjects:@"one",@"two",@"three", nil]; //末尾的nil表示结束符 NSArray * arr2 = [[NSArray alloc]initWithArray:arr1]; //通过已存在的数组实例化新数组 //类方法: NSArray * arr3 = [NSArray arrayWithObjects:@"one",@"two",@"three", nil]; NSArray * arr4 = [NSArray arrayWithArray:arr3]; //Xcode新版本的便捷方法: NSArray * arr5 = @[@"one",@"two",@"three"]; //类似于NSString * str = @"wanger";且此时数组结尾无nil!
OC数组的一些常用方法:
//NSArray常用方法:
NSArray *arr = [NSArray arrayWithObjects:@"one",@"two",@"three",nil];
//求元素个数:count
NSUInteger count = [arr count];
NSLog(@"count = %lu",count);
//获取某位置元素
id obj = [arr objectAtIndex:2];
NSLog(@"%@",obj);
//其实这个方法很鸡肋。arr[index]效果一样
NSLog(@"%@",arr[2]);
//获取某元素的索引
NSInteger index = [arr indexOfObject:@"one"];
NSLog(@"index = %lu",index);
//判断该数组是否包含某元素
BOOL tag = [arr containsObject:@"two"];
if(tag==YES)
{
NSLog(@"嗯,包含了。");
}else if (tag==NO)
{
NSLog(@"没包含。");
}
//获取数组最后一个元素
id obj2 = [arr lastObject];
NSLog(@"lastObject为 %@",obj2);
//将数组各元素连接成字符串对象
NSString *str = [arr componentsJoinedByString:@"+"];
NSLog(@"%@",str);
//将字符串通过分隔符转换成数组
NSString * str1 = @"welcome to shenzhen";
NSArray *arr1 = [str1 componentsSeparatedByString:@" "];
NSLog(@"%lu",[arr1 count]);
NSString *str2 = @"Hi,wang.weclome";
id seqSet = [NSCharacterSet characterSetWithCharactersInString:@",."];
NSArray *arr2 = [str2 componentsSeparatedByCharactersInSet:seqSet];
NSLog(@"%lu",[arr2 count]);
NSLog(@"%@",arr2);
NSString *str3 = @"yes i am a bad body";
NSArray *arr3 = [str3 componentsSeparatedByString:@" "];
int i;
NSMutableString *mStr = [NSMutableString stringWithUTF8String:""];
for (i=(int)[arr3 count]-1; i>=0; i--)
{
[mStr appendString:arr3[i]];
[mStr appendString:@" "];
}
NSLog(@"%@",mStr);
OC遍历数组的3种方法:
第3种要重点掌握!
//数组遍历 NSArray *arr1 = [NSArray arrayWithObjects:@"one",@"two",@"three",nil]; //1.最基本原始方法:for循环 //2.迭代器 NSEnumerator *erator = [arr1 objectEnumerator]; id obj; while ((obj=[erator nextObject])!=nil) { NSLog(@"%@",obj); } //3.增强型for循环 //for(对象类型 对象名 in 列表) //优点:不需要开发者判断结束条件,自动结束 for (id obj in arr1) { NSLog(@"%@",obj); }
标签:
原文地址:http://www.cnblogs.com/wangerxiansheng/p/4301938.html