数组对象NSArray
数组对象的创建:
+ (instancetype)array //空数组 + (instancetype)arrayWithObject:(ObjectType)anObject //一个对象元素的数组 + (instancetype)arrayWithObjects:(ObjectType)firstObj, … //多个对象元素的数组(最后一个参数为nil)
字面值:
NSArray * arr = @[@"hello", @10, @YES]; //常量方式
注意:只能存储OC对象,数值需要封装成对象,nil需要封装成NSNull
基本操作:
@property(readonly) NSUInteger count - (BOOL)containsObject:(ObjectType)anObject @property(nonatomic, readonly) ObjectType firstObject @property(nonatomic, readonly) ObjectType lastObject - (ObjectType)objectAtIndex:(NSUInteger)index - (NSUInteger)indexOfObject:(ObjectType)anObject
文件/URL操作相关:
+ (NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)aPath + (NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)aURL - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)flag
数组的遍历方式一:C语言方式
for ( int i=0; i<arr.count; i++) { NSLog(@"%@", arr[i]); }
数组的遍历方式二:
for ( id obj in arr4) { NSUInteger i = [arr4 indexOfObject:obj]; NSLog(@"index:%lu %@", i, obj); }
注意:这种遍历方式应用在可变数组时,不要在 遍历过程中改变数组
可变数组对象
NSMutableArray用于描述可变数组对象,是NSArray的子类
添加:
- (void)addObject:(ObjectType)anObject - (void)addObjectsFromArray:(NSArray<ObjectType> *)otherArray - (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index
删除:
- (void)removeAllObjects - (void)removeLastObject - (void)removeObjectAtIndex:(NSUInteger)index
集合对象
NSSet用于描述集合对象,子类为NSMutableSet
集合与数组的区别:1)集合不支持下标取成员 2)集合中不能有重复对象
集合对象的创建:
+ (instancetype)set + (instancetype)setWithArray:(NSArray<ObjectType> *)array + (instancetype)setWithObject:(ObjectType)object + (instancetype)setWithObjects:(ObjectType)firstObj, firstObj, ...
集合对象的常见操作:
@property(readonly) NSUInteger count @property(readonly, copy) NSArray < ObjectType > *allObjects - (ObjectType)anyObject - (BOOL)containsObject:(ObjectType)anObject
可变集合对象的操作:
- (void)addObject:(ObjectType)object - (void)removeObject:(ObjectType)object - (void)removeAllObjects - (void)addObjectsFromArray:(NSArray<ObjectType> *)array
其他集合对象:
可变集合对象NSMutableSet
索引集合NSIndexSet
字符集合NSCharacterSet
...
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。