NSArray是OC中的數組類,相比較C語言的數組它可以存放不同類型的數據可以動態的添加和刪除數組元素,同時使用的時候也需要注意,NSArray只能存放OC對象,并且是有順序的,不能存放非OC類,比如int、foat、dounule、char、enum、struct等。我們初始化完畢之后, 它里面的內容就永遠是固定的, 不能刪除里面的元素, 也不能再往里面添加元素。
獲取集合元素個數
- (NSUInteger)count;獲得index位置的元素
- (id)objectAtIndex:(NSUInteger)index;是否包含某一個元素
- (BOOL)containsObject:(id)anObject;返回第一/最后一個元素
- (id)firstObject; - (id)lastObject;查找anObject元素在數組中的位置(如果找不到,返回-1)
- (NSUInteger)indexOfObject:(id)anObject;在range范圍內查找anObject元素在數組中的位置
- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range;讓集合里面的所有元素都執行aSelector這個方法
- (void)makeObjectsPerformSelector:(SEL)aSelector;- (void)makeObjectsPerformSelector:(SEL)aSelector withObject:(id)argument;遍歷, 就是將NSArray里面的所有元素一個一個取出來查看
//普通遍歷for (int i = 0; i<array.count; i++) { }//快速遍歷for (id obj in array) { }//Block遍歷[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { //之前我們也提到過這個方法}];用separator作拼接符將數組元素拼接成一個字符串
- (NSString *)componentsJoinedByString:(NSString *)separator;我們對比NSString的方法:
將字符串用separator作為分隔符切割成數組元素
- (NSArray *)componentsSeparatedByString:(NSString *)separator;NSMutableArray是NSArray的子類,NSArray是不可變的, 一旦初始化完畢后, 它里面的內容就永遠是固定的, 不能刪除里面的元素, 也不能再往里面添加元素,NSMutableArray是可變的, 隨時可以往里面添加/更改/刪除元素。
添加一個元素
- (void)addObject:(id)object;添加otherArray的全部元素到當前數組中
- (void)addObjectsFromArray:(NSArray *)array;在index位置插入一個元素
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;刪除最后一個元素
- (void)removeLastObject;刪除所有的元素
- (void)removeAllObjects;刪除index位置的元素
- (void)removeObjectAtIndex:(NSUInteger)index;刪除特定的元素
- (void)removeObject:(id)object;刪除range范圍內的所有元素
- (void)removeObjectsInRange:(NSRange)range;用anObject替換index位置對應的元素
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;交換idx1和idx2位置的元素
- (void)exchangeObjectAtIndex:(NSUInteger)idx1 withObjectAtIndex:(NSUInteger)idx2;新聞熱點
疑難解答