NSArray與NSSet

NSArray與NSSet
NSArray:有序的集合,存儲的元素在一個整塊的內存中並按序排列;
NSSet:無序的集合,散列存儲。
讀developer.apple關於NSSet的解釋:You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower than with sets.
就是說,如果搜索一個元素,NSSet的效率會比NSArray高。爲什麼呢?道理比較簡單:hash!NSSet中元素的存儲和訪問都是一個hash的過程。比如你要存儲元素A,一個hash算法直接就能直接找到A應該存儲的位置;同樣,當你要訪問A時,一個hash過程就能找到A存儲的位置。而對於NSArray,若想知道A到底在不在數組中,則需要一個一個元素比較,顯然效率沒了。


循環使用整個NSArray內的對象是非常常用的了,而且最近我在研究究竟怎麼能方便的把NSArray存入Core Data,所以這更是必要了,看看如下的方法吧:

1,Objective-C 2.0法,最應該使用的

NSArray *aArray; //我們的Array,假設他已經初始化有內容了
 for(id innerObj in aArray) //id可以由其他對象類型替代
{
//也就是說, 在循環中的參數innerObj就是aArray中的對象
//由於NSArray中只能儲存對象,所以我們使用id作爲內涵對象的類型,其實就是個指針了
//而且如果NSArray中的內容不一致,id更不會出現衝突
}

2,C的老方法,不推薦,低性能

NSArray *aArray; //我們的Array,假設他已經初始化有內容了
 for(int i=0;i<[aArray count]; i++)
{
[[aArray objectAtIndex:i] 然後作你想作的事情]; //做愛 作的事情...
}

3, 用NSEnumerator(不知道怎麼翻譯阿….)

 NSEnumerator* myIterator = [myArray reverseObjectEnumerator];
 id anObject;
 while( anObject = [myIterator nextObject]) //每次讀取“逐讀器”的下一個對象
 {
     //anObject和剛纔的innerObj是一個意思,但是看看多了這麼多行
 }


三種集合類來收集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;
- (id)objectAtIndex:(int)index;                     //  NSString *s1=[[myarray objectAtIndex: 0];
- (void)makeObjectsPerformSelector:(SEL)aSelector;
- (NSArray *)sortedArrayUsingSelector:(SEL)aSelector;
- (id)lastObject; // returns nil if there are no objects in the array (convenient)
注:
類方法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];

    //- (unsigned) Count;數組所包含對象個數;
    NSLog(@"self.dataArray cound:%d",[self.dataArray count]);

    //- (id) objectAtIndex: (unsigned int) index;獲取指定索引處的對象;
    NSLog(@"self.dataArray cound 2:%@",[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];   

    //Copy and sort

    //NSMutableArray *newArray = [[NSMutableArray alloc] init];
    NSArray *oldArray = [NSArray arrayWithObjects:

NSMutableArray
Mutable version of NSArray.
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(int)index;
- (void)removeObjectAtIndex:(int)index;
- (void)removeAllObjects;

-----給數組分配容量-----
    //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
key-value, key-value, ..... 一系列鍵值對。
key(鍵)在整個dictionary是唯一的,通過key可以查詢其對應的一個或多個value(值)。
Hash table. Look up objects using a key to get a value.
Immutable. You cannot add or remove objects to it once it’s created.
Keys are objects which must implement.  Keys are usually NSString objects.
- (NSUInteger)hash & - (BOOL)isEqual:(NSObject *)obj
Important methods:
+ dictionaryWithObjectsAndKeys: (id)firstObject, ...;
- (int)count;
- (id)objectForKey:(id)key;
- (NSArray *)allKeys;
- (NSArray *)allValues;
 -----創建字典 -----
    //- (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 *)dictionary;
- (void)setObject:(id)anObject forKey:(id)key;
- (void)removeObjectForKey:(id)key;
- (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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章