IOS中數(shù)組的使用(NSArray, NSSet, NSDictionary)

一、Foundation framework中用于收集cocoa對象(NSObject對象)的三種集合分別是:

NSArray 用于對象有序集合(數(shù)組)
NSSet 用于對象無序集合(集合)

NSDictionary用于鍵值映射(字典)

以上三種集合類是不可變的(一旦初始化后,就不能改變)

以下是對應(yīng)的三種可變集合類(這三種可變集合類是對應(yīng)上面三種集合類的子類):

NSMutableArray
NSMutableSet
NSMutableDictionary

注:這些集合類只能收集cocoa對象(NSOjbect對象),如果想保存一些原始的C數(shù)據(jù)(例如,int, float, double, BOOL等),則需要將這些原始的C數(shù)據(jù)封裝成NSNumber類型的,NSNumber對象是cocoa對象,可以被保存在集合類中。

=================== NSArray ====================

Ordered collection of objects. Immutable(you cannot add or remove objects to it once it’s created)
Important methods:

  • (id)arrayWithObjects:(id)firstObject, ...; // nil terminated
  • (int)count; // 得到array中的對象個(gè)數(shù)

  • (id)objectAtIndex:(int)index; // 得到索引為i的對象

  • (BOOL)containsObject:(id)anObject; // 當(dāng)anObject出現(xiàn)在array中,則返回yes(實(shí)際是通過isEqual:方法來判斷)

  • (unsigned)indexOfObject:(id)anObject; // 查找array中的anObject,并返回其最小索引值。沒找到返回NSNotFound.

  • (void)makeObjectsPerformSelector:(SEL)aSelector;

  • (NSArray *)sortedArrayUsingSelector:(SEL)aSelector;

  • (id)lastObject; // 得到array中最后一個(gè)對象。如果array中沒有任何對象存在,則返回nil
    注:
    類方法arrayWithObjects 可以創(chuàng)建an autoreleased NSArray of the items.例如
    @implementation MyObject

  • (NSArray *)coolCats {
    return [NSArray arrayWithObjects:@“Steve”, @“Ankush”, @“Sean”, nil];
    }
    @end
    Other convenient create with methods (all return autoreleased objects):
    [NSString stringWithFormat:@“Meaning of %@ is %d”, @“l(fā)ife”, 42];
    [NSDictionary dictionaryWithObjectsAndKeys:ankush, @“TA”, janestudent, @“Student”, nil];
    [NSArray arrayWithContentsOfFile:(NSString *)path];
    -----創(chuàng)建數(shù)組 -----
    NSArray *array = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",nil];

    self.dataArray = array;
    [array release];

    NSLog(@"self.dataArray count is:%d",[self.dataArray count]);

    NSLog(@"self.dataArray index 2 is:%@",[self.dataArray objectAtIndex:2]);

------ 從一個(gè)數(shù)組拷貝數(shù)據(jù)到另一數(shù)組(可變數(shù)級) -------

//arrayWithArray:
NSArray *array1 = [[NSArray alloc] init];
NSMutableArray *MutableArray = [[NSMutableArray alloc] init];
NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSLog(@"array:%@",array);
MutableArray = [NSMutableArray arrayWithArray:array];
NSLog(@"MutableArray:%@",MutableArray);

array1 = [NSArray arrayWithArray:array];
NSLog(@"array1:%@",array1);

//Copy

//id obj;
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSArray *oldArray = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];

NSLog(@"oldArray:%@",oldArray);
for(int i = 0; i < [oldArray count]; i++) {        
    obj = [[oldArray objectAtIndex:i] copy];
    [newArray addObject: obj];
}

NSLog(@"newArray:%@", newArray);
[newArray release];



//快速枚舉
NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSArray *oldArray = [NSArray arrayWithObjects:
                     @"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];   
NSLog(@"oldArray:%@",oldArray);

for(id obj in oldArray)
{
    [newArray addObject: obj];
}

NSLog(@"newArray:%@", newArray);
[newArray release];   

//Deep copy

NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSArray *oldArray = [NSArray arrayWithObjects:
                     @"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];   
NSLog(@"oldArray:%@",oldArray);   
newArray = (NSMutableArray*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef)oldArray, kCFPropertyListMutableContainers);
NSLog(@"newArray:%@", newArray);
[newArray release];   

=================== NSMutableArray ====================
Mutable version of NSArray.

  • (void)addObject:(id)anObject; // 在array最后添加anObject, 添加nil是非法的.

  • (void)addObjectsFromArray:(NSArray *)otherArray; //在array最后把otherArray中的對象依次添加進(jìn)去。

  • (void)insertObject:(id)anObject atIndex:(int)index; //在索引index處插入anObject, 若index被占用,會把之后的object向后移。

  • (void)removeObjectAtIndex:(int)index; //刪除index處的對象,后面的對象依次向前移。

  • (void)removeObject:(id)anObject; // 刪除所有和anObject相等的對象,同樣使用isEqual:作為相等比較方法.

  • (void)removeAllObjects;

注:我們不能把nil加到array中。但有時(shí)候我們真想給array加一個(gè)空的對象,可以使用NSNull來做這件事。如:

[myArray addObject:[NSNull null]];

-----給數(shù)組分配容量-----
//NSArray *array;
array = [NSMutableArray arrayWithCapacity:20];

-----在數(shù)組末尾添加對象-----
//- (void) addObject: (id) anObject;
//NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
[array addObject:@"Four"];
NSLog(@"array:%@",array);

-----刪除數(shù)組中指定索引處對象-----
//-(void) removeObjectAtIndex: (unsigned) index;
//NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
[array removeObjectAtIndex:1];
NSLog(@"array:%@",array);

----- 數(shù)組枚舉-----
//1、- (NSEnumerator *)objectEnumerator; //從前向后
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
NSEnumerator *enumerator;
enumerator = [array objectEnumerator];

id thingie;
while (thingie = [enumerator nextObject]) {
    NSLog(@"thingie:%@",thingie);
}

//2、- (NSEnumerator *)reverseObjectEnumerator; //從后向前
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
NSEnumerator *enumerator;
enumerator = [array reverseObjectEnumerator];

id object;
while (object = [enumerator nextObject]) {
    NSLog(@"object:%@",object);
}

//3、快速枚舉
NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
for(NSString *string in array) {
NSLog(@"string:%@",string);
}

----- NSValue(對任何對象進(jìn)行包裝)-----
//將NSRect放入NSArray中
NSMutableArray *array = [[NSMutableArray alloc] init];
NSValue *value;
CGRect rect = CGRectMake(0, 0, 320, 480);
value = [NSValue valueWithBytes:&rect objCType:@encode(CGRect)];
[array addObject:value];
NSLog(@"array:%@",array);
//從Array中 提取
value = [array objectAtIndex:0];
[value getValue:&rect];
NSLog(@"value:%@",value);

----★使用NSMutableArray要防止內(nèi)存泄露★------
NSObject* p1 = [[NSObject alloc] init];
NSObject* p2 = [[NSObject alloc] init];
NSMutableArray* objectsArray = [[NSMutableArray alloc] init];

[objectsArray addObject:p1];
NSLog(@"p1 count:%d", [p1 retainCount]);//輸出 2,也就是執(zhí)行追加對象后,對象的計(jì)數(shù)器也被加1
//[p1 release];
//NSLog(@"p1 count:%d", [p1 retainCount]);

//同樣做數(shù)組替換時(shí)
[objectsArray replaceObjectAtIndex:0 withObject:p2];
NSLog(@"p2 count:%d", [p2 retainCount]);//輸出 2,同樣也是2
NSLog(@"p1 count:%d", [p1 retainCount]);//輸出 1,對象p1仍然存在
//[p2 release];
//NSLog(@"p2 count:%d", [p2 retainCount]);

//執(zhí)行清空數(shù)組
[objectsArray removeAllObjects];
NSLog(@"p2 count:%d", [p2 retainCount]);//輸出 1,對象p2仍然存在
//[p2 release];

由此可知,每次執(zhí)行上面的數(shù)組操作后,要執(zhí)行對象release,如上面注釋中的語句,才能保證內(nèi)存不泄露。

NSSet
Unordered collection of objects.
Immutable. You cannot add or remove objects to it once it’s created.
Important methods:

  • setWithObjects:(id)firstObj, ...; // nil terminated
  • (int)count;
  • (BOOL)containsObject:(id)anObject;
  • (id)anyObject;
  • (void)makeObjectsPerformSelector:(SEL)aSelector;
  • (id)member:(id)anObject; // uses isEqual: and returns a matching object (if any)

NSMutableSet
Mutable version of NSSet.

  • (NSMutableSet *)set;
  • (void)addObject:(id)anObject;
  • (void)removeObject:(id)anObject;
  • (void)removeAllObjects;
  • (void)unionSet:(NSSet *)otherSet;
  • (void)minusSet:(NSSet *)otherSet;
  • (void)intersectSet:(NSSet *)otherSet;

NSDictionary

一個(gè)dictionary就是key-value對的集合。 key是字符串(NSString),value是對象指針。
key在整個(gè)dictionary是唯一的。通過方法objectForKey:來獲得對應(yīng)于某個(gè)key的一個(gè)或多個(gè)value(值)。
NSDictionary在創(chuàng)建時(shí),其中所有的key和對應(yīng)的value都存在了。你可以訪問其內(nèi)容,但不可以修改。
dictionary使用hash表來實(shí)現(xiàn),所以查找速度很快。

  • (NSUInteger)hash & - (BOOL)isEqual:(NSObject *)obj
    Important methods:
  • dictionaryWithObjectsAndKeys: (id)firstObject, ...;
  • (int)count; // 返回有多少對key-value
  • (id)objectForKey:(id)key; //返回和key相關(guān)聯(lián)的value。 如果沒有和key相關(guān)聯(lián)的value,則返回nil。
  • (NSArray *)allKeys; // 返回一個(gè)包含所有key的array
  • (NSArray *)allValues;
  • NSEnumerator *)keyEnumerator; //這個(gè)方法是從一個(gè) dictionary 中得到一個(gè) key 的迭代器.

Enumerators 也就是 iterators 或 enumerations.我們可以使用它來一步一步迭代出集合中的所 有成員.
下面是我們可能使用它來列舉所有的 key- ‐vaule 對
NSEnumerator *e = [myDict keyEnumerator];
for (NSString *s in e) {
NSLog(@"key is %@, value is %@", s, [myDict objectForKey:s]);
}
注:NSArray 也有一個(gè)類似的方法得到 array 的成員迭代 器 : objectEnumerator

-----創(chuàng)建字典 -----
- (id) initWithObjectsAndKeys;
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"One",@"1",@"Two",@"2",@"Three",@"3",nil];
NSString *string = [dictionary objectForKey:@"One"];
NSLog(@"string:%@",string);
NSLog(@"dictionary:%@",dictionary);
[dictionary release];

NSMutableDictionary
Mutable version of NSDictionary.
NSMutableDictionary是NSDictionary的子類。創(chuàng)建后,允許用戶添加和刪除key和value。

  • (NSMutableDictionary *)dictionary; // 創(chuàng)建一個(gè)空的dictionary
  • (void)setObject:(id)anObject forKey:(id)key; // 使用key和anObject組成一條記錄添加到dictionary中
    // 如果key已存在,則會先移除舊的key-value,然后再添加新的key-value。
  • (void)removeObjectForKey:(id)key; // 從dictionary中刪除一條記錄,key以及和它對應(yīng)的value
  • (void)removeAllObjects;
  • (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
    -----創(chuàng)建可變字典 -----
    //創(chuàng)建
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    //添加字典
    [dictionary setObject:@"One" forKey:@"1"];
    [dictionary setObject:@"Two" forKey:@"2"];
    [dictionary setObject:@"Three" forKey:@"3"];
    [dictionary setObject:@"Four" forKey:@"4"];
    NSLog(@"dictionary:%@",dictionary);
    //刪除指定的字典
    [dictionary removeObjectForKey:@"3"];
    NSLog(@"dictionary:%@",dictionary);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容