W e S D
0 1

[Objective-C] 008_Foundation框架之NSArray与NSMutableArray

  在Cocoa Foundation中NSArray和NSMutableArray 用于对象有序集合,NSArray和NSMutableArray类最大的区别是:NSArray是不可变,NSMutableArray是可变的。它们只能存储Cocoa对象(NSObject对象),如果想保存一些原始的C数据(如:int,float,double,BOOL等),则需要将这些原始的C数据封装NSNumber类型,它们的下标是从0开始,下面是NSArray和NSMutableArray类的一些常用初级操作。

1.NSArray 初始化

NSArray *array = [[NSArray alloc] initWithObjects:@"SuperDo.Horse",@"SuperDo.Mount",@"SuperDo.AC",nil];
//用现有的数组进行初始化
NSArray *array1 = [NSArray arrayWithArray:array];

 2.NSArray 快速枚举

NSArray *array = [[NSArray alloc] initWithObjects:@"SuperDo.Horse",@"SuperDo.Mount",@"SuperDo.AC",nil];
for (NSString *str in array) {
    NSLog(@"%@",str);
}

3.NSMutableArray 简单排序

NSMutableArray*array = [[NSMutableArray alloc] initWithObjects:@"SuperDo.Horse",@"SuperDo.Mount",@"SuperDo.AC",nil];
//数组中的元素按照字符串大小排序:
[array sortUsingSelector:@selector(compare:)];
NSLog(@"sorted array:%@",array);

4.字符串 ---> NSArray

NSString *string = [[NSString alloc] initWithString:@"A|B|C|D"];
NSLog(@"string:%@",string);
NSArray *array = [string componentsSeparatedByString:@"|"];
NSLog(@"array:%@",array);

5.NSArray ---> 字符串

NSArray *array = [[NSArray alloc] initWithObjects:@"A",@"B",@"C",@"D",nil];
NSString *string = [array componentsJoinedByString:@"|"];
NSLog(@"string:%@",string);

6.元素操作

//插入元素
NSMutableArray *array = [NSMutableArray arrayWithObjects:
                         @"One",@"Two",@"Three",nil];
[array addObject:@"Four"];
NSLog(@"array:%@",array);

//删除元素
[array removeObjectAtIndex:1];
NSLog(@"array:%@",array);

//枚举元素(从前向后)
NSEnumerator  *enumerator = [array objectEnumerator];
id next;
while (next = [enumerator nextObject]) {
    NSLog(@"object------》:%@",next);
}

//枚举元素(从后向前)
NSEnumerator *enumerator = [array reverseObjectEnumerator];
id object;
while (object = [enumerator nextObject]) {
    NSLog(@"object------》:%@",object);
}

 

 

本站文章为 宝宝巴士 SD.Team 原创,转载务必在明显处注明:(作者官方网站: 宝宝巴士 
转载自【宝宝巴士SuperDo团队】 原文链接: http://www.cnblogs.com/superdo/p/4594178.html

 

 

posted @ 2015-06-22 23:43  SD.Team  阅读(223)  评论(0编辑  收藏  举报