NSArray 的创建
NSArray 的创建可以使用arrayWithObjects这个消息,他可以装任意Object对象,最后一个nil代表数组的结束。
[NSArray arrayWithObjects:@"str1",@"str2",@"str3",@"str4", nil];
NSArray的长度和索引
在Objective-C里数组对象 count消息获得数组的长度。而objectAtIndex消息获得数组相应位置的对象。
例子如下
#import <Foundation/Foundation.h> int main(int argc, constchar * argv[]) { @autoreleasepool { NSArray *array =[NSArray arrayWithObjects:@"str1",@"str2",@"str3",@"str4", nil]; // array=[NSArray arrayWithArray:@"OK"];只有一个元素的数组 long int count = [array count]; NSLog(@"数组元素的个数为%ld",count); //求数组中元素的个数 id obj = [array objectAtIndex:(count-1)];//count-1为所需的最大的值减去 NSLog(@"%@",obj); for (int i=0; i<[array count]; i++) { NSLog(@"%@",[array objectAtIndex:i]); } NSLog(@"数组逆序输出如下"); for (long i = [array count ]-1;i>=0; i--) { NSLog(@"%@",[array objectAtIndex:i]); } NSArray *myArray; NSDate *aDate = [NSDatedistantFuture]; NSLog(@"%@",aDate); NSValue *aValue = [NSNumbernumberWithInt:5]; NSLog(@"%@",aValue); NSString *aString = @"a string"; myArray = [NSArrayarrayWithObjects:aDate, aValue, aString, nil];//创建数组 NSLog(@"%@",myArray); for (int i=0; i<[myArray count] ; i++) { NSLog(@"%@",[myArray objectAtIndex:i]); } } return0; }