user1085596 user1085596 - 5 months ago 13
Objective-C Question

BOOL inside of NSMutableArray gives wrong answer

I have an NSMutableArray that contains a BOOL. Elements are added via:

addObject:@[@YES, sectionInfo.header, myFeedSource.header


I then walk thru the array as follows:

for (int i=0; i<revealController.headersSelected.count; i++) {
isActive = [revealController.headersSelected[i][0] boolValue];
MLog(@"Active %@",revealController.headersSelected[i][0]);
MLog(@"class %@",[revealController.headersSelected[i][0] class]);
MLog(@"converted %d",[revealController.headersSelected[i][0] boolValue]);
if (isActive) {
MLog(@"Yes");
}else {
MLog(@"No");
}
if (revealController.headersSelected[i][0]) {
MLog(@"Yes");
}else {
MLog(@"No");
}
if (revealController.headersSelected[i][0]>0) {
MLog(@"Yes");
}else {
MLog(@"No");
}


The output is:

Active 0
class __NSCFBoolean
converted 0
No
Yes
Yes


The only way I can get it to see the correct value of the sub-element is to convert it into a var with:

isActive = [revealController.headersSelected[i][0] boolValue];


The value of this BOOL is set inside of the For..Next loop via replaceObjectAtIndex:

What am I missing here? Why doesn't it see the correct value of the BOOL?

I've printed out the whole array before and after, the value changes from 1 to 0.

Answer

Comments on your output:

Active 0              This is truth
class __NSCFBoolean   This is truth
converted 0           This is truth
No                    This is truth
Yes      This is a lie, because you're testing for pointer existence
Yes      This is a lie, because you're testing the pointer isn't a zero

So, I'd guess you're editing something which is a copy sometimes and not updating it back into your data structure, and / or you need to be careful with unpacking the NSNumber instances.