-6

所以编译器告诉我 using[arrayName objectAtIndex:i]是一个无效的表达式,但文档中的所有内容都告诉我我做得对。我很困惑。为什么不让我以这种方式访问​​数组?

-(IBAction)textWasEdited:(id)sender
{
   int i = 0;
   do
   {
       //do stuff
       i++
   } while([tipPercentages objectAtIndex:i] != Nil);
}

我看不出这段代码有什么问题!有点把我的头发拉在这里。

4

2 回答 2

4

返回 nil是不可能的objectAtIndex:,因此您的代码毫无意义。没有 NSArray 可以包含 nil。如果tipPercentages不是 NSArray(例如,如果它是 C 数组),则它无法响应objectAtIndex:.

于 2013-02-20T21:03:07.573 回答
1

好的,我不完全清楚你在这里做什么,但我认为你的问题是你的代码一直试图访问数组末尾之后的数组元素(因为objectAtIndex:不能返回 nil)。你想要更像这样的东西:

- (IBAction)textWasEdited:(id)sender {
   __block int i = 0;
   [tipPercentages enumerateObjectsWithBlock:^(id object, NSUInteger idx, BOOL *stop) {
       //do stuff
       i++
   }];
}

或者,如果您真的想维护原始循环:

- (IBAction)textWasEdited:(id)sender {
   int i = 0;
   for (; i < [tipPercentages count]; i++) {
       id object = [tipPercentages objectAtIndex:i];
       //do stuff
   }];
}

我很确定你在调试器中所做的任何被它拒绝的事情都是一个附带问题——如果你的代码正在编译,编译器不会告诉你你的代码是无效的。

于 2013-02-20T21:32:35.037 回答