如何使用字符串值获取NSArray中对象的索引?

编程入门 行业动态 更新时间:2024-10-27 20:27:22
本文介绍了如何使用字符串值获取NSArray中对象的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想获取NSMutableArray类别中的对象的索引.

I want to get the index of an object within the NSMutableArray of categories.

类别对象具有属性"category_title",我希望能够通过传递category_title的值来获取索引.

The category object has an attribute "category_title" and I want to be able to get the index by passing the value of category_title.

我已经浏览了文档,找不到解决此问题的简单方法.

I have looked through the docs and can't find a simple way to go about this.

推荐答案

NSArray不保证您只能存储给定对象的一个​​副本,因此必须确保自己处理(或使用NSOrderedSet).

NSArray does not guarantee that you can only store one copy of a given object, so you have to make sure that you handle that yourself (or use NSOrderedSet).

也就是说,这里有几种方法.如果您的类别对象实现isEqual:来匹配category_title,则可以只使用-indexOfObject:.

That said, there are a couple approaches here. If your category objects implement isEqual: to match category_title, then you can just use -indexOfObject:.

如果您不能这样做(因为类别对象使用不同的相等性定义),请使用-indexOfObjectPassingTest:.它需要一个块,您可以在其中进行任何您想定义测试"的测试-在这种情况下,测试category_title字符串相等性.

If you can't do that (because the category objects use a different definition of equality), use -indexOfObjectPassingTest:. It takes a block in which you can do whatever test you want to define your "test" - in this case, testing category_title string equality.

请注意,这些都是为NSArray声明的,因此,如果仅查看NSMutableArray标头/文档,就不会看到它们.

Note that these are all declared for NSArray, so you won't see them if you are only looking at the NSMutableArray header/documentation.

代码示例.这假定具有NSString属性categoryTitle的类CASCategory的对象(我不能让自己在ivar名称中加下划线:-):

Code sample. This assumes objects of class CASCategory with an NSString property categoryTitle (I can't bring myself to put underscores in an ivar name :-):

CASCategory *cat1 = [[CASCategory alloc] init]; [cat1 setCategoryTitle:@"foo"]; CASCategory *cat2 = [[CASCategory alloc] init]; [cat2 setCategoryTitle:@"bar"]; CASCategory *cat3 = [[CASCategory alloc] init]; [cat3 setCategoryTitle:@"baz"]; NSMutableArray *array = [NSMutableArray arrayWithObjects:cat1, cat2, cat3, nil]; [cat1 release]; [cat2 release]; [cat3 release]; NSUInteger barIndex = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[(CASCategory *)obj categoryTitle] isEqualToString:@"bar"]) { *stop = YES; return YES; } return NO; }]; if (barIndex != NSNotFound) { NSLog(@"The title of category at index %lu is %@", barIndex, [[array objectAtIndex:barIndex] categoryTitle]); } else { NSLog(@"Not found"); }

更多推荐

如何使用字符串值获取NSArray中对象的索引?

本文发布于:2023-10-10 11:25:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1478530.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   索引   对象   字符串值   NSArray

发布评论

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

>www.elefans.com

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