Objective-C 集合之NSArray的常用方法

不可变数组NSArray(可存储不同类型的对象)

1.属性

@property(readonly) NSUInteger count

@property(nonatomic, readonly) ObjectType firstObject

@property(nonatomicreadonlyObjectType lastObject

2.方法

- (BOOL)containsObject:(ObjectType)anObject

判断数组中是否包含某个对象

- (ObjectType)objectAtIndex:(NSUInteger)index

获取数组中索引为index的元素

- (void)getObjects:(ObjectType  _Nonnull [])aBuffer

获取数组里面的元素到缓存aBuffer中

- (NSEnumerator<ObjectType> *)objectEnumerator

得到数组的枚举器

用法:

NSEnumerator *enumerator = [myArray objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject]) {
    
}

- (NSEnumerator<ObjectType> *)reverseObjectEnumerator

得到数组的反序枚举器,用法如上

- (NSUInteger)indexOfObject:(ObjectType)anObject

得到对象anObject在数组中的索引index

- (BOOL)isEqualToArray:(NSArray<ObjectType> *)otherArray

判断两个数组是否相同

- (NSArray<ObjectType> *)arrayByAddingObject:(ObjectType)anObject

添加anObject对象到数组最后一个元素

- (NSArray<ObjectType> *)arrayByAddingObjectsFromArray:(NSArray<ObjectType> *)otherArray  

将otherArray数组的元素添加到数组的末尾 

- (NSArray<ObjectType> *)sortedArrayUsingSelector:(SEL)comparator

使用comparator比较方法对数组进行排序

- (NSString *)componentsJoinedByString:(NSString *)separator

将数组元素用separator分隔符连接成一个字符串

- (void)setValue:(id)value
              forKey:(NSString *)key

- (id)valueForKey:(NSString *)key

 

 可变数组NSMutableArray

- (void)addObject:(ObjectType)anObject

添加元素

- (void)insertObject:(ObjectType)anObject
                 atIndex:(NSUInteger)index

在插入元素anObject到索引为index的位置上

- (void)replaceObjectAtIndex:(NSUInteger)index
                          withObject:(ObjectType)anObject

将索引为index的元素替换为anObject对象

- (void)removeAllObjects

移除数组中所有元素

- (void)removeLastObject

移除数组中最后一个元素

- (void)removeObject:(ObjectType)anObject

移除数组中和对象anObject一样的元素

- (void)removeObjectAtIndex:(NSUInteger)index

移除索引为index的元素

- (void)setArray:(NSArray<ObjectType> *)otherArray

将数组内容替换为otherArray数组

- (void)exchangeObjectAtIndex:(NSUInteger)idx1
                  withObjectAtIndex:(NSUInteger)idx2

将索引为idx1的元素和索引为idx2的元素相交换

- (void)sortUsingSelector:(SEL)comparator

 使用comparator比较方法进行排序

 

 


转载请注明:作者SmithJackyson

原文地址:https://www.cnblogs.com/smithjackyson/p/5071058.html