检查NSArray中的自定义对象中是否存在NSString(Check if NSString exists in custom object in NSArray)

系统教程 行业动态 更新时间:2024-06-14 17:03:52
检查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];

更多推荐

本文发布于:2023-04-24 12:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/f6ed3d770f29a44f82ed88e0375f178e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   是否存在   象中   NSArray   NSString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!