http://blog.csdn.net/ztp800201/article/details/7777715
一、NSArray是静态数组,创建后数组内容及长度不能再修改。
实例:
-
-
-
NSArray6 *city = [NSArray arrayWithObjects:@"上海",@"广州",@"重庆",nil];
-
-
for(int i=0; i < [city count];i++){
-
NSLog(@"%@",[city objectAtIndex:i]);
-
}
运行结果:
上海
广州
重庆
NSArray常用方法:
-
+(id)arrayWithObjects:obj1,obj2,...nil
-
-(BOOL)containsObject:obj
-
-(NSUInterger)count
-
-(NSUInterger)indexOfObject:obj
-
-(id)ObjectAtIndex:i
-
-(void)makeObjectsPerformSelector:(SEL)selector
-
-(NSArray*)sortedArrayUsingSelector:(SEL)selector
-
-(BOOL)writeToFile:path atomically:(BOOL)flag
二、NSMutableArray是动态数组,可以动态增加数组中的元素,同样NSMutableArray是NSArray的子类。
实例:
-
-
NSMutableArray *nsma = [MSMutableArray arrayWithCapacity:5];
-
for(int i=0;i<=50;i++) {
-
if( i%3 == 0 ) {
-
[nsma addObject:[NSNumber numberWithInteger:i]];
-
}
-
}
-
-
-
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:30
-
Name:Lee,Age:23
-
Name:Alex,Age:26
-
排序后:
-
Name:Alex,Age:26
-
Name:Lee,Age:23
-
Name:Sam,Age:30
NSMutableArray常用方法:
-
+(id)array
-
+(id)arrayWithCapacity:size
-
-(id)initWithCapacity:size
-
-(void)addObject:obj
-
-(void)insertObject:obj atIndex:i
-
-(void)replaceObjectAtIndex:i withObject:obj
-
-(void)removeObject:obj
-
-(void)removeObjectAtIndex:i
-
-(void)sortUsingSelector:(SEL)selector
阅读(520) | 评论(0) | 转发(0) |