开发者

why does '[self.pickerSubArray indexOfObject:self.txtSubCategory.text]' return '2147483647'?

why does '[self.pickerSubArray indexOfObject:self.txtSubCategory.text]' return '2147483647'; wh开发者_StackOverflow中文版ile the same string value argument '[self.pickerSubArray indexOfObject:@"Mark"]' brings up 4, as desired?


The Apple docs for NSArray (which I assume your object is, based on the name) say that indexOfObject: returns NSNotFound if the object does not match any in the array. NSNotFound is itself defined as NSIntegerMax which, as others have pointed out, is the value that you are getting back.

indexOfObject: uses isEqual: to compare the items, so in theory if the text is the same then it should be working. Perhaps the text is actually different in some way that you haven't noticed, such as case ("Mark" vs. "mark") or extra padding ("Mark" vs. "Mark ").


indexOfObject: returns NSNotFound if it can't find your exact object. NSNotFound is defined as NSIntegerMax, which is 2147483647.

Why is it doing that? I'm pretty sure indexOfObject: tests for an identical object, not an object with identical content. e.g.

NSString *mark1 = [NSString stringWithString:@"Mark"];
NSString *mark2 = [NSString stringWithString:@"Mark"];

mark1 is not necissarily equal to mark2, because they're two different objects.

NSString *mark1 = [NSString stringWithObject:@"Mark"];
NSString *mark2 = mark1;

mark1 is equal to mark2;

BUT! Since the compiler is trying to minimize the memory footprint, it turns all literal strings in your code into one constant string. Which is why [[NSArray arrayWithObject:@"Mark"] indexOfObject:@"Mark"] works, but [[NSArray arrayWithObject:@"Mark"] indexOfObject:textField.text] doesn't work even if the text in textField.text is "Mark".

How do you fix it... well, indexOfObject: from the docs it looks like indexOfObject: is based on isEqual: so you should test if [self.txtSubCategory.text isEqual:@"Mark"]. to rule out the wrong value or a disconnected outlet, etc. After that, you may have to refactor to not use indexOfObject:


Just a guess about the number origin - it's a bad integer conversion. It was very probably meant to return -1.

That kindof leads me to believe that you might have found some badness in underlying libraries/languages.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜