挑战:检查模型对象数组是否包含模型属性的最佳方法 Objective-C

Challenge : Best way to check if model object array contains properties of model in Objective-C

型号 = 国家代码

@property (nonatomic, retain) NSString * abbreviation;
@property (nonatomic, retain) NSNumber * code;
@property (nonatomic, retain) NSString * name;

模型数组 = CountryCodesArray

问题: 我有国家代码,例如:81

我想检查 81 是否在我的模型数组中??

查询: 我想让这个过程更有效率。 我不想像 :

这样在循环中签入
for (CountryCode * countcode in Countrycodes) {
        NSLog(@"\n%@", countcode.code);
}

尝试了快速枚举,但崩溃了,有什么建议吗??

BOOL isCodePresent = [[Countrycodes valueForKeyPath:@"CountryCode.code"] containsObject:@"81"];

提前致谢。

无需循环,您可以使用 filteredArrayUsingPredicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"code == 81"];
NSArray *filtered = [countryCodesArray filteredArrayUsingPredicate:predicate];

那么如果你需要对象:

CountryCode *countcode = (CountryCode*)[filtered objectAtIndex:0];