NSArray和NSMutableArray
- 數(shù)組是一個(gè)有序的元素序列渊鞋,支持隨機(jī)存取凸克。索引從0開始,索引越界會(huì)拋出運(yùn)行時(shí)異常蒲障。
- NSArray被定義為Class锄码,是引用類型,拷貝時(shí)具有引用語義晌涕。
- NSArray的元素必須是對(duì)象滋捶,即NSObject或其子類:
1.如為基本數(shù)值類型,必須用NSNumber封裝為對(duì)象類型余黎。
2.如為C語言結(jié)構(gòu)類型重窟,必須用NSValue封裝為對(duì)象類型。
3.數(shù)組元素可以是不同對(duì)象類型惧财,可能會(huì)有類型不安全巡扇。 - NSArray具有常量性:長(zhǎng)度和指針都不能更改,但是指針指向的對(duì)象內(nèi)部是可以更改的垮衷。
- NSMutableArray支持更改數(shù)組長(zhǎng)度和元素厅翔。是NSArray的子類。
- 提前預(yù)估好capacity有利于提高效率
- 盡量避免使用insertObject:<#(nonnull id)#> atIndex:<#(NSUInteger)#>和removeObjectAtIndex:<#(NSUInteger)#>等操作搀突,涉及大量?jī)?nèi)存操作刀闷。
初始化方式
//工廠方式
NSArray *array1=[NSArray arrayWithObjects:@"Shanghai",@"Beijing",@"New York",@"Paris", nil];
//初始化器
NSArray *array2=[[NSArray alloc] initWithObjects:@"Shanghai",@"Beijing",@"New York",@"Paris", nil];
//字面常量方式
NSArray *array3=@[@"Shanghai",@"Beijing",@"New York",@"Paris"];-
遍歷(由快到慢)
//快速枚舉
for ( NSObject* obj in array)
{
//do something...
obj
}//迭代器模式 NSEnumerator *enumerator = [array objectEnumerator]; NSObject* item; while (item = [enumerator nextObject]) { //do something } //for循環(huán) for (int i=0; i<array.count; i++) { //do something }
NSSet和NSMutableSet
- NSSet是一個(gè)無序集合,其儲(chǔ)存的對(duì)象不能重復(fù)。
NSSet被定義為Class甸昏,是引用類型顽分,拷貝時(shí)具有引用語義。
NSSet為常量集合長(zhǎng)度和指針不能修改施蜜,NSMutableSet為可變集合
-
code
NSSet *set1 =[NSSet setWithObjects:@"Shanghai",@"Beijing",@"New York",@"Paris", nil];
NSMutableSet *set2 =[NSMutableSet setWithObjects:@"Shanghai",@"Beijing",@"New York",@"Paris", nil];[set2 addObject:@"London"]; [set2 addObject:@"Paris"]; [set2 removeObject:@"Beijing"]; if([set2 containsObject:@"Shanghai"]) { NSLog(@"set2 contains Shanghai"); } for(NSString* item in set2) { NSLog(@"%@", item); }
NSDictionary和NSMutableDictionary
- NSDictionary是一個(gè)存儲(chǔ)key-value的無序集合卒蘸,其中key值不可重復(fù),value不限制翻默。
NSDictionary被定義為Class缸沃,是引用類型,拷貝時(shí)具有引用語義修械。
NSDictionary為常量集合長(zhǎng)度和指針不能修改和泌,NSMutableDictionary為可變集合
-
code
BLNPoint *p1=[[BLNPoint alloc] initWithX:10 WithY:20];
BLNPoint *p2=[[BLNPoint alloc] initWithX:20 WithY:40];
BLNPoint *p3=[[BLNPoint alloc] initWithX:30 WithY:60];
BLNPoint *p4=[[BLNPoint alloc] initWithX:40 WithY:80];
BLNPoint *p5=[[BLNPoint alloc] initWithX:50 WithY:100];NSDictionary *dictionary1 = @{@"Shanghai" : p1, @"Beijing" : p2,@"New York" : p3,@"Paris" : p4}; NSMutableDictionary *dictionary2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:p1,@"Shanghai",p2,@"Beijing",p3,@"New York",p4,@"Paris",nil]; NSLog(@"dictionary1 count: %lu", dictionary1.count); NSLog(@"dictionary2 count: %lu", dictionary2.count); BLNPoint* result1=[dictionary1 objectForKey:@"Beijing"]; BLNPoint* result2=dictionary1[@"Shanghai"]; NSLog(@"%@", result1); NSLog(@"%@", result2); for(NSString* key in dictionary1) { id object=dictionary1[key]; NSLog(@"key:%@, object:%@", key, object); } [dictionary2 setObject:p5 forKey:@"London"]; [dictionary2 removeObjectForKey:@"Shanghai"]; NSLog(@"dictionary2: %@", dictionary2);