0

在下面的代码中,我正在检查 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);
4

1 回答 1

3

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

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

它现在应该返回YES

于 2012-05-20T04:39:31.353 回答