检查NSArray中的自定义对象中是否存在NSString(Check if NSString exists in custom object in NSArray)
我有一个带有Store对象的NSArray 。 每个Store对象都有两个NSString对象; StoreID和Name 。 我想快速检查一下这个带有Store对象的NSArray是否存在ID。
例:
Store *s1 = [[Store alloc] init]; s1.name = @"Some Name"; s1.id = @"123ABC"; Store *s2 = [[Store alloc] init]; s2.name = @"Some Other Name"; s2.id = @"ABC123"; NSArray *array = [[NSArray alloc] initWithObjects:s1, s2, nil]; NSString *myIdOne = @"ABCDEF"; NSString *myIdTwo = @"123ABC"; BOOL myIdOneExists = ...? BOOL myIdTwoExists = ...?它的...? 我需要弄清楚。 我知道我可以使用for循环并在发现时中断...但这似乎是一种令人讨厌的方法,因为NSArray可能包含数千个对象,......理论上。 所以我想知道一个更好的解决方案。
I have an NSArray with Store objects. Each Store object has two NSString objects; StoreID and Name. I would like to check quickly if an ID exists in this NSArray with Store objects.
Example:
Store *s1 = [[Store alloc] init]; s1.name = @"Some Name"; s1.id = @"123ABC"; Store *s2 = [[Store alloc] init]; s2.name = @"Some Other Name"; s2.id = @"ABC123"; NSArray *array = [[NSArray alloc] initWithObjects:s1, s2, nil]; NSString *myIdOne = @"ABCDEF"; NSString *myIdTwo = @"123ABC"; BOOL myIdOneExists = ...? BOOL myIdTwoExists = ...?Its the ...? I need to figure out. I know I can do this using a for loop and break when found... but this seems to me like an nasty approach since the NSArray could contain thousands of objects,... theoretically. So I would like to know about a better solution.
最满意答案
尝试这个:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@",@"id", myID]; NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate]; if (filteredArray.count > 0) Store *store = [filteredArray objectAtIndex:0];Try this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K == %@",@"id", myID]; NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate]; if (filteredArray.count > 0) Store *store = [filteredArray objectAtIndex:0];更多推荐
发布评论