IOS中数组的使用(NSArray, NSSet, NSDictionary)

一、Foundation framework中用于收集cocoa对象(NSObject对象)的三种集合分别是:

NSArray 用于对象有序集合(数组)
NSSet 用于对象无序集合(集合)

NSDictionary用于键值映射(字典)

以上三种集合类是不可变的(一旦初始化后,就不能改变)

以下是对应的三种可变集合类(这三种可变集合类是对应上面三种集合类的子类):

NSMutableArray
NSMutableSet
NSMutableDictionary

注:这些集合类只能收集cocoa对象(NSOjbect对象),如果想保存一些原始的C数据(例如,int, float, double, BOOL等),则需要将这些原始的C数据封装成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中的对象个数

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

  • (BOOL)containsObject:(id)anObject; // 当anObject出现在array中,则返回yes(实际是通过isEqual:方法来判断)

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

  • (void)makeObjectsPerformSelector:(SEL)aSelector;

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

  • (id)lastObject; // 得到array中最后一个对象。如果array中没有任何对象存在,则返回nil
    注:
    类方法arrayWithObjects 可以创建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”, @“life”, 42];
    [NSDictionary dictionaryWithObjectsAndKeys:ankush, @“TA”, janestudent, @“Student”, nil];
    [NSArray arrayWithContentsOfFile:(NSString *)path];
    -----创建数组 -----
    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]);

------ 从一个数组拷贝数据到另一数组(可变数级) -------

//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中的对象依次添加进去。

  • (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中。但有时候我们真想给array加一个空的对象,可以使用NSNull来做这件事。如:

[myArray addObject:[NSNull null]];

-----给数组分配容量-----
//NSArray *array;
array = [NSMutableArray arrayWithCapacity:20];

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

-----删除数组中指定索引处对象-----
//-(void) removeObjectAtIndex: (unsigned) index;
//NSMutableArray *array = [NSMutableArray arrayWithObjects:@"One",@"Two",@"Three",nil];
[array removeObjectAtIndex:1];
NSLog(@"array:%@",array);

----- 数组枚举-----
//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(对任何对象进行包装)-----
//将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要防止内存泄露★------
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,也就是执行追加对象后,对象的计数器也被加1
//[p1 release];
//NSLog(@"p1 count:%d", [p1 retainCount]);

//同样做数组替换时
[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]);

//执行清空数组
[objectsArray removeAllObjects];
NSLog(@"p2 count:%d", [p2 retainCount]);//输出 1,对象p2仍然存在
//[p2 release];

由此可知,每次执行上面的数组操作后,要执行对象release,如上面注释中的语句,才能保证内存不泄露。

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

一个dictionary就是key-value对的集合。 key是字符串(NSString),value是对象指针。
key在整个dictionary是唯一的。通过方法objectForKey:来获得对应于某个key的一个或多个value(值)。
NSDictionary在创建时,其中所有的key和对应的value都存在了。你可以访问其内容,但不可以修改。
dictionary使用hash表来实现,所以查找速度很快。

  • (NSUInteger)hash & - (BOOL)isEqual:(NSObject *)obj
    Important methods:
  • dictionaryWithObjectsAndKeys: (id)firstObject, ...;
  • (int)count; // 返回有多少对key-value
  • (id)objectForKey:(id)key; //返回和key相关联的value。 如果没有和key相关联的value,则返回nil。
  • (NSArray *)allKeys; // 返回一个包含所有key的array
  • (NSArray *)allValues;
  • NSEnumerator *)keyEnumerator; //这个方法是从一个 dictionary 中得到一个 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 也有一个类似的方法得到 array 的成员迭代 器 : objectEnumerator

-----创建字典 -----
- (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的子类。创建后,允许用户添加和删除key和value。

  • (NSMutableDictionary *)dictionary; // 创建一个空的dictionary
  • (void)setObject:(id)anObject forKey:(id)key; // 使用key和anObject组成一条记录添加到dictionary中
    // 如果key已存在,则会先移除旧的key-value,然后再添加新的key-value。
  • (void)removeObjectForKey:(id)key; // 从dictionary中删除一条记录,key以及和它对应的value
  • (void)removeAllObjects;
  • (void)addEntriesFromDictionary:(NSDictionary *)otherDictionary;
    -----创建可变字典 -----
    //创建
    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);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,829评论 1 331
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,603评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,846评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,600评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,780评论 3 272
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,695评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,136评论 2 293
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,862评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,453评论 0 229
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,942评论 2 233
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,347评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,790评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,293评论 3 221
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,839评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,448评论 0 181
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,564评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,623评论 2 249

推荐阅读更多精彩内容