在处理我的NSMutableArray时,似乎我的containsObject不起作用

时间:2012-05-20 04:33:30

标签: objective-c

在下面的代码中,我正在检查queso是否在购物清单中。起初它不是,但后来我用addObject方法添加它。

问题是在我将它添加到数组之前的任何一种方式,并且在我添加它之后,我仍然得到相同的NO('0')回答。这是我的代码。任何人都可以告诉我在我的代码中我做错了什么。这就像我第二次称它,它被跳过了。

// Create some grocries
NSString *salsa = [NSString stringWithString:@"Texas Texas Salsa"];
NSString *queso = [NSString stringWithString:@"The Best Queso"];
NSString *chips = [NSString stringWithString:@"Our Chips"];

// Create the mutable array
NSMutableArray *groceryList = [NSMutableArray array];

// Add groceries to the list
[groceryList addObject:chips];
[groceryList addObject:salsa];

//Try out the containsObject: method for my array
BOOL quesoIsOnTheList = [groceryList containsObject:queso];
NSLog(@"Is queso on the list? %i", quesoIsOnTheList);

// Forgot to put queso in the query, add it to the top of the list    
[groceryList insertObject:queso atIndex:0];

// Now check again after queso has been added
NSLog(@"Now is queso on the list? %i", quesoIsOnTheList);

1 个答案:

答案 0 :(得分:3)

您在数组中插入queso之前定义了quesoIsOnTheList,并且在添加queso之后,您正在记录相同的变量,所以当然它仍然是NO。用以下内容替换第二个日志:

NSLog(@"Now is queso on the list? %i",[groceryList containsObject:queso]);

现在应该返回YES