一、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,則需要先建立一個臨時檔案
二、NSMutableArray是動態數組,可以動態增加數組中的元素,同樣NSMutableArray是NSArray的子類。
執行個體:
//用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 <Foundation/Foundation.h>@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 <Foundation/Foundation.h>#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:30Name:Lee,Age:23Name:Alex,Age:26排序後:Name:Alex,Age:26Name:Lee,Age:23Name:Sam,Age:30
NSMutableArray常用方法:
+(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指示的比較方法進行排序