NSArray創建和遍歷

用來存儲有序列表,是不可變的。

不能存儲C語言中的基本數據類型,如:int、float、enum、struct、也不能存儲nil

// 創建NSArray的常用方法
+ (id)array;
+ (id)arrayWithObject:(id)anObject;
+ (id)arrayWithObjects:(idfirstObj), ...
+ (id)arrayWithArray:(NSArray *)array
- (id)initWithObjects:(id)firstObj, ...
- (id)initWithArray:(NSArray *)array

+ (id)arrayWithContentsOfFile:(NSString *)path
+ (id)arrayWithContentsOfURL:(NSURL *)url
- (id)initWithContentsOfFile:(NSString *)path
- initWithContentsOfURL:(NSURL *)url
// 創建一個空數組
NSArray *array = [NSArray array];

// 創建有1個元素的數組
NSArray *array = [NSArray arrayWithObject:@"123"];

// 創建多個元素的數組
array = [NSArray arrayWithObjects:@"a", @"n", @"c"];
//NSArray 查詢
- (NSUInteger)count; //獲取集合元素個數
- (BOOL)containsObject:(id)anObject;//是否包含某一個元素
- (id)lastObject;//返回最後一個元素
- (id)objectAtIndex:(NSUInteger)index; //返回index

- (NSUInteger)indexOfObject:(id)anObject;//查找元素的位置
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range;//在range範圍內查找元素的位置
// 數組內存管理
Student *stu1 = [[Student alloc]init];
Student *stu2 = [[Student alloc]init];
Student *stu3 = [[Student alloc]init];

NSLog(@"stu1 : %i", [stu1 retainCount]); // stu1 : 1

// 當把一個對象加進數組時,這個對象的計數器加1,當數組銷燬時,會對數組的元素進行release
NSArray *array = [[NSArray alloc] initWithObjects:stu1, stu2, stu3];

NSLog(@"stu1 : %i", [stu1 retainCount]); // stu1 : 2


[array release];
//NSArray比較
- (BOOL)isEqualToArray:(NSArray *)otherArray;//比較兩個集合內容是否相同
- (id)firstObjectCommonWithArray:(NSArray *)otherArrary//返回兩個集合中第一個相同的對象元素
// 給元素髮送消息
- (void)makeObjectsPerformSelector:(SEL)aSelector
- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument://讓集合裏的所有元素都執行aSelector這個方法
// NSArray 遍歷
// 1. 普通遍歷
NSUInteger count = [array count];
for (int i = 0; i < count; i++) {
    id obj = [array objectAtIndex:i];
    // id == void *
}

// 2. 快速遍歷
int i = 0;
for (id obj in array) {
    NSLog(@"%i - %@", i, obj);
    i ++;
}

// 3. 迭代器遍歷
    //查看NSEnumerator的用法
// 獲取數組的迭代器
NSEnumerator *enumerator = [array objectEnumerator];
// 獲取反序迭代器
NSEnumerator *enumerator = [array reverseObjectEnumerator];
// 獲取下一個需要遍歷的元素
while (obj = [enumerator nextObject]) {
    NSLog(@"obj = %@", obj);
}

/*
    獲取迭代器所有對象,是取出沒有被遍歷過的對象
*/
NSArray *array2 = [enumerator allObjects];
NSLog(@"array2 : %@", array2);

// 4. block遍歷
[array enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
    NSLog(@"%@ - %zi", object, index);
    if (index == 1) {
        *stop = YES;//停止遍歷,利用指針,修改外邊的BOOL變量
    }
}]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章