Objective-C之數組


數組遍歷的兩種方式

 
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //也可以用:NSArray *array = [NSArray arrayWithObjects:@"One",@"Two",@"Three",nil];  NSArray* array = [[NSArray alloc] initWithObjects: @"One",@"Two",@"Three",nil]; //nil起結束標志的作用  NSLog(@"%lu", [array count]); //第一種遍歷方法: for(int i = 0; i < array.count; i++) { //如果知道數組里存的對象如本題則可以用NSString接收,如果不知道則可以用id接收 //id obj = [array objectAtIndex:i]; NSString* str = [array objectAtIndex:i]; NSLog(@"%@", str); } //第二種變量方法:快速枚舉 for(NSString* obj in array) { NSLog(@"%@", obj); } NSArray* array2 = [NSArray arrayWithArray:array]; [pool drain]; return 0; }

字符串分割成數組對象與連接

#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSString* str = @"one,two,three,four,five"; //分割字符創為數組,下例以“,”分割 NSArray* array = [str componentsSeparatedByString:@","]; for(NSString* obj in array) { NSLog(@"%@", obj); } //鏈接字符串,下例以空格連接 str = [array componentsJoinedByString:@" "]; NSLog(@"%@", str); [pool drain]; return 0; }

運行結果:

 

2012-06-24 23:18:51.394 demo8[412:707] one

2012-06-24 23:18:51.397 demo8[412:707] two

2012-06-24 23:18:51.398 demo8[412:707] three

2012-06-24 23:18:51.399 demo8[412:707] four

2012-06-24 23:18:51.401 demo8[412:707] five

2012-06-24 23:18:51.401 demo8[412:707] one two three four five

 

數組的插入:

NSArray只能管理OC的對象,它管理的這些對象可以是不同類型的。

數組對每一個對象具有擁有權。

#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //往數組中插入內容 NSMutableArray* array1 = [NSMutableArray arrayWithCapacity:0]; [array1 addObject:@"one"]; NSLog(@"%@", array1); [array1 addObject:@"three"]; //都是插在末尾 NSLog(@"%@", array1); [array1 insertObject:@"two" atIndex:1]; //插入索引為幾的位置 for(NSString* obj in array1) { NSLog(@"%@", obj); } //移除 [array1 removeObjectAtIndex:2]; NSLog(@"%@", array1); [pool drain]; return 0; }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM