NSArray功能扩展
2020-10-14 本文已影响0人
傲视苍穹
获取数组中的对象
/// 获取数组中的对象
/// @param index 为正值 左->右 , 负值 左<-右
- (id)exp_objAtIndex:(NSInteger)index;
例子 :
NSArray *arry = @[@"1",@"2",@"3"];
//左->右
NSString * str0 = [arry exp_objAtIndex:0];
NSString * str1 = [arry exp_objAtIndex:1];
NSString * str2 = [arry exp_objAtIndex:2];
NSLog(@"====%@===%@====%@",str0,str1,str2);
//左<-右
NSString * str_1 = [arry exp_objAtIndex:-1];
NSString * str_2 = [arry exp_objAtIndex:-2];
NSString * str_3 = [arry exp_objAtIndex:-3];
NSLog(@"====%@===%@====%@",str_1,str_2,str_3);
运行结果 :
image.png数组是否为空
/// 数组是否为空
- (BOOL)isEmpty;
例子 :
NSArray *arry = @[@"1",@"2",@"3"];
if (arry.isEmpty) {
NSLog(@"空");
}else{
NSLog(@"有值");
}
运行结果 :
image.png数组映射
/// 映射
/// @param mapper 映射规则
- (NSArray *)mapper:(id(^)(id obj))mapper;
例子 :
NSArray *arry = @[@"1",@"2",@"3"];
NSArray *mapperArray = [arry mapper:^id _Nonnull(NSString * obj) {
return [obj stringByAppendingString:@"_1"];
}];
NSLog(@"======%@",mapperArray);
运行结果 :
image.png数组筛选
/// 筛选
/// @param filter 筛选规则
- (NSArray *)filter:(BOOL(^)(id obj))filter;
例子 :
NSArray *arry = @[@"1",@"2",@"3"];
NSArray *filterArray = [arry filter:^BOOL(NSString * obj) {
return [obj isEqualToString:@"2"];
}];
NSLog(@"======%@",filterArray);
运行结果 :
image.png数组元素拼接
/// 数组元素拼接
-(NSString *(^)(NSString *separator))joinedByString;
例子 :
NSArray *arry = @[@"1",@"2",@"3"];
NSString *str = arry.joinedByString(@",");
NSLog(@"======%@",str);
运行结果 :
image.png源码
.h
//
// NSArray+Expand.h
// 数组的扩展
//
// Created by 崔志伟 on 2020/10/13.
// Copyright © 2020 崔志伟. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSArray (Expand)
/// 获取数组中的对象
/// @param index 为正值 左->右 , 负值 左<-右
- (id)exp_objAtIndex:(NSInteger)index;
/// 数组是否为空
- (BOOL)isEmpty;
/// 映射
/// @param mapper 映射规则
- (NSArray *)mapper:(id(^)(id obj))mapper;
/// 筛选
/// @param filter 筛选规则
- (NSArray *)filter:(BOOL(^)(id obj))filter;
/// 数组元素拼接
-(NSString *(^)(NSString *separator))joinedByString;
@end
NS_ASSUME_NONNULL_END
.m
//
// NSArray+Expand.m
// 数组的扩展
//
// Created by 崔志伟 on 2020/10/13.
// Copyright © 2020 崔志伟. All rights reserved.
//
#import "NSArray+Expand.h"
@implementation NSArray (Expand)
- (id)exp_objAtIndex:(NSInteger)index{
if (index >=0) {
return [self objectAtIndex:index];
}else{
return [self objectAtIndex:self.count +index];
}
}
- (BOOL)isEmpty{
return self.count<=0;
}
- (NSArray*)mapper:(id(^)(id obj))mapper{
NSMutableArray *array = [NSMutableArray array];
for (id item in self) {
if (mapper) {
id newItem = mapper(item);
[array addObject:newItem];
}
}
return array.copy;
}
- (NSArray*)filter:(BOOL(^)(id obj))filter{
NSMutableArray *array = [NSMutableArray array];
for (id item in self) {
if (filter) {
BOOL isFit = filter(item);
if (isFit) {
[array addObject:item];
}
}
}
return array.copy;
}
-(NSString *(^)(NSString *separator))joinedByString{
return ^(NSString *separator) {
return [self componentsJoinedByString:separator];
};
}
@end