我如何检查对象已存在于数组中

时间:2013-06-21 10:35:41

标签: ios

我做错了什么

    [mutableArry addObject:[NSNumber numberWithInt:questionNumber]];
    NSLog(@"mutableArry=%@",mutableArry);
      NSLog(@" question not complete  count=%d",mutableArry.count);

    if (mutableArry.count==25) {
        NSLog(@"25 question complete%d",mutableArry.count);
    }

    NSString *str= [NSString stringWithFormat:@"%d",questionNumber];
    NSLog(@"str=%@",str);

  //  array = [NSArray arrayWithObjects: @"Nicola", @"Margherita", @"Luciano", @"Silvia", nil];
  if ([mutableArry containsObject:str]) {  //YES
    NSLog(@"Results");
  }

5 个答案:

答案 0 :(得分:3)

检查你的两行:

[mutableArry addObject:[NSNumber numberWithInt:questionNumber]];

[mutableArry containsObject:str]

溶液:

将questionNumber添加为NSString或查找数字:)应该带来更多成功;)

NSMutableArray *ary = [NSMutableArray arrayWithObject:[NSNumber numberWithInt:25]];
NSString *str= [NSString stringWithFormat:@"%d",25];

if([ary containsObject:[NSNumber numberWithInt:25]])
    NSLog(@"ary contains object - number");

if([ary containsObject:str])
    NSLog(@"ary contains object - string");
else
    NSLog(@"ary doesn't contain object - string");

日志:
ary包含对象 - 数字
ary不包含对象 - 字符串

答案 1 :(得分:3)

您尝试比较两个不同的对象。 <{1}}对象不是你放入数组的对象,所以你可以比较它。

所以你可以这样做:

str

仅供参考:您的命名惯例不太好......

答案 2 :(得分:1)

if ([mutableArry containsObject:[NSNumber numberWithInt:questionNumber]])
{
    NSLog(@"Results");
}

答案 3 :(得分:0)

您应该执行以下操作,而不是最后一个if语句。

for (NSString *object in mutableArry) {
    if (object isEqualToString:str) {
        NSLog(@"Match");
    }
}

答案 4 :(得分:0)

通过以下方式替换您的代码。您正在添加NSNumber个实例并比较NSString

[mutableArry addObject:[[NSNumber numberWithInt:questionNumber]stringValue]];
NSLog(@"mutableArry=%@",mutableArry);
NSLog(@" question not complete  count=%d",mutableArry.count);

if (mutableArry.count==25) {
    NSLog(@"25 question complete%d",mutableArry.count);
}

NSString *str= [NSString stringWithFormat:@"%d",questionNumber];
NSLog(@"str=%@",str);

//  array = [NSArray arrayWithObjects: @"Nicola", @"Margherita",                                       @"Luciano", @"Silvia", nil];
if ([mutableArry containsObject:str]) // YES
{
    NSLog(@"Results");
}