Objective-C NSArray

簡介

NSArray是OC中的數組類,相比較C語言的數組它可以存放不同類型的數據可以動態的添加和刪除數組元素,同時使用的時候也需要注意,NSArray只能存放OC對象,並且是有順序的,不能存放非OC類,比如int、foat、dounule、char、enum、struct等。我們初始化完畢之後, 它裏面的內容就永遠是固定的, 不能刪除裏面的元素, 也不能再往裏面添加元素。

創建

+ (instancetype)array;
+ (instancetype)arrayWithObject:(id)anObject;
+ (instancetype)arrayWithObjects:(id)firstObj;
+ (instancetype)arrayWithArray:(NSArray *)array;

+ (id)arrayWithContentsOfFile:(NSString *)path;
+ (id)arrayWithContentsOfURL:(NSURL *)url;

//將一個NSArray保存到文件中
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically;

檢索

獲取集合元素個數

- (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

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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章