重温OC,发现好些之前忽视的小细节,简单的梳理一下。
NSSet
NSArray
- 基础数据类型可以直接用系统的compare
NSMutableArray *array=[NSMutableArray arrayWithCapacity:2];
[array addObject:@"xiaoming"];
[array addObject:@"xiaohong"];
[array addObject:@"xiaozhang"];
[array addObject:@"xiaofang"];
[array addObject:@"xiaocui"];
[array sortUsingSelector:@selector(compare:)];
- 非基础数据类型有多种排序方法
NSMutableArray *bookArray=[NSMutableArray array];
Book *book1=[Book bookWithName:@"chinese" price:19];
Book *book2=[Book bookWithName:@"math" price:16];
Book *book3=[Book bookWithName:@"english" price:15];
[bookArray addObject:book1];
[bookArray addObject:book2];
[bookArray addObject:book3];
1.block排序
[bookArray sortUsingComparator:^NSComparisonResult(Book* obj1, Book* obj2) {
if (obj1.price < obj2.price) {
return NSOrderedAscending;
}else if (obj1.price > obj2.price) {
return NSOrderedDescending;
}else{
return NSOrderedSame;
}
}];
2. SEL排序
[bookArray sortUsingSelector:@selector(compare:)];
3. 描述排序
NSSortDescriptor *descriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"price" ascending:YES];
NSSortDescriptor *descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[bookArray sortUsingDescriptors:@[descriptor1,descriptor2]];
- 快速遍历
用block遍历对大数据会比较有优势
[bookArray enumerateObjectsUsingBlock:^(Book* obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"%ld--%@",obj.price,obj.name);
}];
//同时block每执行一次后,
//会判断idx相对于当前数组是否越界
//越界则不招待,否则执行
//所以删除时可以考虑反向遍历
[bookArray enumerateObjectsWithOptions:NSEnumerationReverse
usingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[bookArray removeObject:obj];
NSLog(@"idx---%ld",idx);
NSLog(@"count---%ld",bookArray.count);
}];
检索判断
检测判断,返回第一个符合条件的数据索引或返加符合条件的数据索引集合
NSUInteger pass = [bookArray indexOfObjectPassingTest:^BOOL(Book *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.price > 25) {
return YES;
}else{
return NO;
}
}];
if (pass == NSNotFound) {
NSLog(@"notFound");
}
NSIndexSet *testSet = [bookArray indexesOfObjectsPassingTest:^BOOL(Book* obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.price> 15) {
return YES;
}else{
return NO;
}
}];
NSLog(@"%ld",testSet.count);
[testSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"======%lu",idx);
}];