一、NSArray是静态数组,创建后数组内容及长度不能再修改。
实例:
//用arrayWithObjects初始化一个不可变的数组对象。
//初始化的值之间使用逗号分开,以nil结束。
NSArray6 *city = [NSArray arrayWithObjects:@"上海",@"广州",@"重庆",nil];
for(int i=0; i < [city count];i++){
NSLog(@"%@",[city objectAtIndex:i]);
}
上海
广州
重庆
NSArray常用方法:
+(id)arrayWithObjects:obj1,obj2,...nil //创建一个新的数组,obj1,obj2,.., 以nil结束。
-(BOOL)containsObject:obj //确定数组中是否包含对象obj
-(NSUInterger)count //数组中元素的个数
-(NSUInterger)indexOfObject:obj //第一个包含obj元素的索引号
-(id)ObjectAtIndex:i //存储在位置i的对象
-(void)makeObjectsPerformSelector:(SEL)selector //将selector提示的消息发送给数组中的每一个元素
-(NSArray*)sortedArrayUsingSelector:(SEL)selector //根据selector提定的比较方法对数组进行排序
-(BOOL)writeToFile:path atomically:(BOOL)flag //将数组写入指定的文件中。如果flag为YES,则需要先创建一个临时文件
//用arrayWithCapacity创建一个长度为5的动态数组
NSMutableArray *nsma = [MSMutableArray arrayWithCapacity:5];
for(int i=0;i<=50;i++) {
if( i%3 == 0 ) {
[nsma addObject:[NSNumber numberWithInteger:i]]; //用addObject给数组nsma增加一个对象
}
}
//输出数组中的元素
for(int i=0;i<[nsma count];i++) {
NSLog(@"%li",(long)[[nsma objectAtIndex] integerValue]);
}
student.h
#import
@interface Student: NSObject {
NSString: *name;
int age;
}
@property (copy,nonatomic) NSString* name;
@property int age;
-(void)print;
-(NSComparisonResult)compareName:(id)element;
@end
StudentTest.m
#import
#import "student.h"
int main( int argc, const char* agrv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Student* stu1 = [[Student alloc] init];
Student* stu2 = [[Student alloc] init];
Student* stu3 = [[Student alloc] init];
[stu1 setName:@"Sam"];
[stu1 setAge:30];
[stu2 setName:@"Lee"];
[stu2 setAge:23];
[stu3 setName:@"Alex"];
[stu3 setAge:26];
NSMutableArray *students = [[NSMutableArray alloc] init];
[students addObject:stu1];
[students addObject:stu2];
[students addObject:stu3];
NSLog(@"排序前:");
for(int i=0; i<[students count];i++) {
Student *stu4 = [students objectAtIndex:i];
NSLog(@"Name:%@,Age:%i",[stu4 name],[stu4 age]);
}
[students sortUsingSelector:@selector(compareName:)];
NSLog(@"排序后:");
for( Student *stu4 in students ) {
NSLog(@"Name:%@,Age:%i", stu4.name, stu4.age);
}
[students release];
[stu1 release];
[sut2 release];
[stu3 release];
[pool drain];
return 0;
}
排序前:
Name:Sam,Age:30
Name:Lee,Age:23
Name:Alex,Age:26
排序后:
Name:Alex,Age:26
Name:Lee,Age:23
Name:Sam,Age:30
+(id)array //创建一个空数组
+(id)arrayWithCapacity:size //创建一个容量为size的数组
-(id)initWithCapacity:size //初始化一个新分配的数,指定容量为size
-(void)addObject:obj //将obj增加到数组中
-(void)insertObject:obj atIndex:i //将obj插入数据的i元素
-(void)replaceObjectAtIndex:i withObject:obj //用obj替换第i个索引的对象
-(void)removeObject:obj //从数组中删除所有是obj的对象
-(void)removeObjectAtIndex:i //从数组中删除索引为i的对象
-(void)sortUsingSelector:(SEL)selector //用selector指示的比较方法进行排序