用法总结:NSArray,NSSet,NSDictionary-备用

时间:2024-06-27 19:05:26
Foundation framework中用于收集cocoa对象(NSObject对象)的三种集合分别是:

NSArray 用于对象有序集合(数组
NSSet 用于对象无序集合      (集合)
NSDictionary用于键值映射(字典
以上三种集合类是不可变的(一旦初始化后,就不能改变)

以下是对应的三种可变集合类(这三种可变集合类是对应上面三种集合类的子类):
NSMutableArray
NSMutableSet  可修改的集合。主要用于集合运算(并集,交集,差集)
NSMutableDictionary 允许用户添加和删除key和value

注:这些集合类只能容纳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];
    NSArray *monthNames = [NSArray arrayWithObjects:@"January",@"February",@"March",@"April",@"May",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]);

注:初始化一个数组时,经常使用initWithObject  和 initWithObjects。没有s的表示使用一个指针初始化NSArray,初始化后,这个NSArray的实例只有一个数据,所以在调用没有s的函数的时候是不能以nil结束的;但是有s的就不一样了,哪怕只有一个数据,或者没有数据,必须使用一个nil结束。

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

//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)

1、NSSet的使用
[NSSet setWithSet:(NSSet *)set]; 用另外一个set对象构造
[NSSet setWithArray:(NSArray *)array];用数组构造
[NSSet setWithObjects:...]:创建集合对象,并且初始化集合中的数值,结尾必需使用nil标志。
[set count] ; 得到这个结合对象的长度。
[set containsObject:...]: 判断这个集合中是否存在传入的对象,返回Bool值。
[set objectEnumerator]: 将集合放入迭代器。
[enumerator nextObject]:得到迭代器中的下一个节点数据,使用while遍历这个迭代器,方可遍历集合对象中的对象。
[set isEqualToSet:objset]:判断两个集合是否完全相等,返回Bool值。
[set isSubsetOfSet:objset]:判断集合中的所有数据是否都相等与objeset集合中,返回Bool值。
[set allObjects];

示例代码:

1.1 以NSArray构造set

  1. NSArray *array = [[NSArray alloc] initWithObjects:@"对象abc",@"rongfzh", @"totogo2010",nil];
  2. NSSet *set3 = [NSSet setWithArray:array];
  3. NSLog(@"%@", set3);

打印:

2012-07-10 09:39:02.015 objectiveC[720:403] {(
    rongfzh,
    "\U5bf9\U8c61abc",
    totogo2010
)}

1.2 set的一些比较方法的使用。

  1. int main(int argc, const char * argv[])
  2. {
  3. @autoreleasepool {
  4. NSSet *set = [NSSet setWithObjects:@"25",@"age",@"张三",@"name",@"男",nil];
  5. NSSet *set1 = [NSSet setWithObjects:@"25",@"age",@"张三",@"name",@"男",@"性别",nil];
  6. NSLog(@"set count:%lu", [set count]);
  7. //判断是否含有age字符串
  8. if([set containsObject:@"age"]) {
  9. NSLog(@"set包含age");
  10. }
  11. //判断set 是否等于set1
  12. if ([set isEqualToSet:set1]) {
  13. NSLog(@"set 等于 set1");
  14. }
  15. //判断set是否是否是set1的子集合
  16. if ([set isSubsetOfSet:set1]) {
  17. NSLog(@"set isSubsetOfSet set1");
  18. }
  19. //获取所有set对象
  20. NSArray *array = [set allObjects];
  21. NSLog(@"array:%@", array);
  22. //迭代遍历
  23. NSEnumerator *enumerator = [set objectEnumerator];
  24. for (NSObject *object in enumerator) {
  25. NSLog(@"set1里的对象:%@", object);
  26. }
  27. }
  28. return 0;
  29. }

打印结果:

2012-07-10 09:50:32.018 objectiveC[939:403] set count:5
2012-07-10 09:50:32.020 objectiveC[939:403] set包含age
2012-07-10 09:50:32.021 objectiveC[939:403] set isSubsetOfSet set1
2012-07-10 09:50:32.023 objectiveC[939:403] array:(
    age,
    25,
    "\U7537",
    "\U5f20\U4e09",
    name
)
2012-07-10 09:50:32.027 objectiveC[939:403] set1里的对象:age
2012-07-10 09:50:32.028 objectiveC[939:403] set1里的对象:25
2012-07-10 09:50:32.028 objectiveC[939:403] set1里的对象:男
2012-07-10 09:50:32.029 objectiveC[939:403] set1里的对象:张三
2012-07-10 09:50:32.029 objectiveC[939:403] set1里的对象:name

===================  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);