NSArray

August 18, 2013   ·   0 Comments

範例1    (動態新增):

NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:@”aa”];
[array addObject:@”bbb”];

NSLog(@”array count==%d”,array.count);

for(int i = 0; i < array.count; i++){
NSLog(@”i=%@”,[array objectAtIndex:i]);
}
[array release];

範例2 (靜態放入值+動態新增)

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@”cc”,@”ddd”,nil];
[array addObject:@”aa”];
[array addObject:@”bbb”];

NSLog(@”array count==%d”,array.count);

for(int i = 0; i < array.count; i++){
NSLog(@”i=%@”,[array objectAtIndex:i]);
}
[array release];

範例3 指定index放入物件,使用insertObject指定位置時,指定的位置必須是 (陣列長度 – 1) 以內的範例值

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@”cc”,@”ddd”,nil];
[array addObject:@”aa”];
[array addObject:@”bbb”];

[array insertObject:@”aaaa” atIndex:4];    //在位置4放入 字串 aaaa

範例4:移除物件

移除指定位置物件
[array removeObjectAtIndex:4];

清除所有物件
[array removeAllObjects];

範例5:將數值放入陣列

int percentage = 40;

// 產生一個NSNumber物件,可以用signed or unsigned char, short int, int, long int, long long int, float, double or BOOL等基本型態產生物件
NSNumber *percentageObject = [NSNumber numberWithFloat:percentage];

//將NSNumber物件放入array
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:percentageObject];

//取出數值
[percentageObject intValue];

範例6:將指定位置的物件替換掉==>replaceObjectAtIndex:索引值(int) withObject:物件(id)

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@”cc”,@”ddd”,nil];
[array addObject:@”aa”];
[array addObject:@”bbb”];

for(int i = 0; i < array.count; i++){
NSLog(@”i=%@”,[array objectAtIndex:i]);
}

[array replaceObjectAtIndex:2 withObject:@”111″];

for(int i = 0; i < array.count; i++){
NSLog(@”i=%@”,[array objectAtIndex:i]);
}
[array release];

shareShare on FacebookShare on Google+Share on LinkedInEmail this to someonePrint this pageBuffer this pageDigg thisFlattr the authorShare on RedditPin on PinterestShare on StumbleUponShare on TumblrTweet about this on Twitter

By


Readers Comments (0)


You must be logged in to post a comment.

PowenKo’s Online Store

powenko_arduinoBook
iOS Tutorial9

Amazon

adsbygoogle

Recent Posts

Categories

Amazon