将 NSString 与数组的 NSString 字段进行匹配
我有一个名为 myObjectArray 的 NSMutableArray,其中包含名为 myObject 的 NSObjects 数组。 myObject 有两个字段(元素?),它们是 NSString 的。像这样:
@interface myObject : NSObject {
NSString * string1;
NSString * string2;
}
我有一个 NSMutableArray ,其中包含大约 50 个这样的对象,所有对象都具有不同的 string1 和 string2 。然后我有一个独立的 NSString 变量,称为 otherString;
有没有一种快速方法可以从 myObjectArray 访问其 string1 与 otherString 匹配的 myObject?
我应该说,这就是我所拥有的,但我想知道是否有更快的方法:
-(void) matchString: {
NSString * testString = otherString;
for(int i=0; i<[myObjectArray count];i++){
myObject * tempobject = [myObjectArray objectAtIndex:i];
NSString * tempString = tempobject.string1;
if ([testString isEqualToString:tempString]) {
// do whatever
}
}
}
I have an NSMutableArray
called myObjectArray which contains and array of NSObjects
called myObject. myObject has two fields (elements?) which are NSString
's. like this:
@interface myObject : NSObject {
NSString * string1;
NSString * string2;
}
I have an NSMutableArray
which contains about 50 of these objects, all with different string1's and string2's. then I have and independent NSString
variable, called otherString;
Is there a fast way to access the myObject from myObjectArray whose string1 matches otherString?
i should say, this is what i have, but i wonder if there is a faster way:
-(void) matchString: {
NSString * testString = otherString;
for(int i=0; i<[myObjectArray count];i++){
myObject * tempobject = [myObjectArray objectAtIndex:i];
NSString * tempString = tempobject.string1;
if ([testString isEqualToString:tempString]) {
// do whatever
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法可以做到这一点,
使用谓词
现在
filteredArray
拥有所有具有string1
的myObject
实例> 匹配otherString
。使用
indexOfObjectPassingTest:
如果有满足条件的对象,
index
会将您指向其索引。否则它将具有值NSNotFound
。如果您希望所有对象都满足条件,您还可以查看
indexesOfObjectsPassingTest:
。There are a few ways you can do this,
Using Predicates
Now
filteredArray
has all themyObject
instances that have theirstring1
matchingotherString
.Using
indexOfObjectPassingTest:
If there is an object that satisfies the condition,
index
will point you to its index. Otherwise it will have the valueNSNotFound
.You can also look at
indexesOfObjectsPassingTest:
if you want all the objects satisfying the condition.