检查NSMutableArray中的值

时间:2012-02-15 09:37:04

标签: iphone objective-c nsmutablearray

我有一个NSMutableArray(contactsArray),内容如下。

{({ContactID = ""; RecordID = 45; Number = "";},
{ContactID = 134;RecordID = 47;Number = PNAPYOEMZH;})}

我有一个自变量说x。我需要检查x是否等于数组中的ContactID

2 个答案:

答案 0 :(得分:1)

你可以使用isEqual来检查数组数据之间的东西,试试这个

if([[yourArray objectAtIndex:theIndex]valueForKey:@"ContactID"] isEqualToNumber [[yourArray objectAtIndex:theIndex]valueForKey:@"RecordID"])
{
NSLog(@"the contact ID matches the Record ID");
}
else
{
NSLog(@"it doesn't match")
}

这里发生的是if句子将数组中的对象与索引或行“theIndex”

中的数据的“ContactId”值与“RecordID”进行比较

希望这个帮助

编辑:由于您将问题编辑为具有变量X,您只需将第二个参数比较器更改为[NSNumber numberWithInt:x]

如果您的X是String类型,则应使用.intValue

答案 1 :(得分:0)

你可以这样做:

NSMutableArray *contactsArray = <the_array>;
int x = <the_value_to_check_against>;

[contactsArray filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id obj, NSDictionary *bindings){
    return ([[obj objectForKey:@"ContactID"] intValue] == x);
}]];

或将谓词更改为:

[contactsArray filterUsingPredicate:[NSPredicate predicateWithFormat:@"self.ContactID == %@", [NSNumber numberWithInt:x]]];