iOS Developer

NSArray的基本使用

2016-12-15  本文已影响83人  Coder007
NSArray基本概念
NSArray创建方式
+ (instancetype)array;
+ (instancetype)arrayWithObject:(ObjectType)anObject;
+ (instancetype)arrayWithObjects:(ObjectType)firstObj, ...;
+ (instancetype)arrayWithArray:(NSArray<ObjectType> *)array;
+ (nullable NSArray<ObjectType> *)arrayWithContentsOfFile:(NSString *)path;
+ (nullable NSArray<ObjectType> *)arrayWithContentsOfURL:(NSURL *)url;
NSArray的注意事项
NSArray的常用方法
NSArray *arr = @[@"123",@"456",@"6777"];

// 获取数组元素个数
NSUInteger count = [arr count];

// 获取index位置的元素
NSString *str1 = [arr objectAtIndex:0];

// 是否包含某一个元素
BOOL isContain = [arr containsObject:@"123"];

// 返回最后一个元素
NSString *str2 = [arr lastObject];

// 返回第一个元素
NSString *str3 = [arr firstObject];

// 查找元素在数组中得位置,如果找不到返回-1
int index = [arr indexOfObject:@"111"];
快速创建方式
NSArray *arr = @[@"123", @"qwe"];
遍历数组
NSArray *arr = @[@"3",@"1",@"4",@"10",@"5"];
// 下标遍历
for (int i = 0; i < arr.count; i++) {
    NSLog(@"%@",arr[i]);
}

// 快速遍历
for (NSString *str in arr) {
    NSLog(@"%@",str);
}

// 使用block遍历
// stop用来控制什么时候遍历停止,*stop = YES 将停止遍历
[arr enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"%@",obj);
}];
给NSArray中所有元素发消息
[arr makeObjectsPerformSelector:@selector(方法名)];
[arr makeObjectsPerformSelector:@selector(方法名:) withObject:@""];
NSArray排序
NSArray *arr = @[@3,@1,@4,@10,@5];
NSArray *newArr1 = [arr sortedArrayUsingSelector:@selector(compare:)];
NSArray *arr = @[@3,@1,@4,@10,@5];
NSArray *newArr2 = [arr sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
     return obj1 > obj2;
}];
NSArray与NSString之间的转换
NSArray *arr = @[@3,@1,@4,@10,@5];
NSString *str = [arr componentsJoinedByString:@"--"];
NSString *str1 = @"3--1--4--10--5";
NSArray *arr1 = [str1 componentsSeparatedByString:@"--"];
NSArray文件读写
NSArray *arr = @[@"123",@"awe11",@"zdxcq"];
[arr writeToFile:@"/Users/coder/Desktop/sublime.plist" atomically:YES];
NSArray *arr1 = [NSArray arrayWithContentsOfFile:@"/Users/coder/Desktop/sublime.plist"];
上一篇下一篇

猜你喜欢

热点阅读