在开发中我们经常会遇到根据某个条件来判断数组中某个元素是否存在的情况,一般我们会使用for 循环,然后在循环里使用if 进行判断。其实我们也可以使用NSPredicate 过滤器来快速实现该功能。
其核心代码如下:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.type == %d", (int)type];
NSArray *results = [devices filteredArrayUsingPredicate:predicate];
return results.count > 0;
NSPredicate 过滤器的更多使用请参考👉:iOS开发 NSPredicate的使用方法
1. 使用示例
Device *device0 = [[Device alloc] init];
device0.mac = @"A1CC2D1F18A7";
device0.type = 1;
Device *device1 = [[Device alloc] init];
device1.mac = @"A1CC2D1F18A8";
device1.type = 2;
NSArray *devices = @[device0, device1];
BOOL exists0 = [Device existsDeviceForMac:@"A1CC2D1F18A8" inDevices:devices];
BOOL exists1 = [Device existsDeviceForType:3 inDevices:devices];
Device *device = [Device deviceForMac:@"A1CC2D1F18A8" inDevices:devices];
NSLog(@"设备[A1CC2D1F18A8] %@ 于设备列表中", exists0 ? @"已存在" : @"不存在");
NSLog(@"设备[类型为3] %@ 于设备列表中", exists1 ? @"已存在" : @"不存在");
NSLog(@"根据MAC地址[A1CC2D1F18A8]获取的设备: %@", device);
2. Device模型类
Device.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Device : NSObject
@property (nonatomic, copy) NSString *mac;
@property (nonatomic, assign) NSInteger type;
#pragma mark - Tool Methods
+ (BOOL)existsDeviceForMac:(NSString *)mac inDevices:(NSArray<Device *> *)devices;
+ (BOOL)existsDeviceForType:(NSInteger)type inDevices:(NSArray<Device *> *)devices;
+ (Device *)deviceForMac:(NSString *)mac inDevices:(NSArray<Device *> *)devices;
@end
NS_ASSUME_NONNULL_END
Device.m
#import "Device.h"
@implementation Device
#pragma mark - Tool Methods
+ (BOOL)existsDeviceForMac:(NSString *)mac inDevices:(NSArray<Device *> *)devices {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.mac LIKE[c] %@", mac];
NSArray *results = [devices filteredArrayUsingPredicate:predicate];
return results.count > 0;
}
+ (BOOL)existsDeviceForType:(NSInteger)type inDevices:(NSArray<Device *> *)devices {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.type == %d", (int)type];
NSArray *results = [devices filteredArrayUsingPredicate:predicate];
return results.count > 0;
}
+ (Device *)deviceForMac:(NSString *)mac inDevices:(NSArray<Device *> *)devices {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.mac LIKE[c] %@", mac];
NSArray *results = [devices filteredArrayUsingPredicate:predicate];
if (results.count > 0) {
return results.firstObject;
}
return nil;
}
@end
|