40

I need to utilize an array of booleans in objective-c. I've got it mostly set up, but the compiler throws a warning at the following statement:

[updated_users replaceObjectAtIndex:index withObject:YES];

This is, I'm sure, because YES is simply not an object; it's a primitive. Regardless, I need to do this, and would greatly appreciate advice on how to accomplish it.

Thanks.

Allyn
  • 20,271
  • 16
  • 57
  • 68

6 Answers6

73

Yep, that's exactly what it is: the NS* containers can only store objective-C objects, not primitive types.

You should be able to accomplish what you want by wrapping it up in an NSNumber:

[updated_users replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]]

or by using @(YES) which wraps a BOOL in an NSNumber

[updated_users replaceObjectAtIndex:index withObject:@(YES)]]

You can then pull out the boolValue:

BOOL mine = [[updated_users objectAtIndex:index] boolValue];

Kevin
  • 16,696
  • 7
  • 51
  • 68
Nick Partridge
  • 1,414
  • 10
  • 11
14

Assuming your array contains valid objects (and is not a c-style array):

#define kNSTrue         ((id) kCFBooleanTrue)
#define kNSFalse        ((id) kCFBooleanFalse)
#define NSBool(x)       ((x) ? kNSTrue : kNSFalse)

[updated_users replaceObjectAtIndex:index withObject:NSBool(YES)];
Andrew Grant
  • 58,260
  • 22
  • 130
  • 143
  • 2
    I'm curious to find out why Nicks answer got so much more support than this one, as this seems more elegant. Can anyone explain the difference? – Chris Apr 10 '13 at 19:33
12

You can either store NSNumbers:

[updated_users replaceObjectAtIndex:index
                         withObject:[NSNumber numberWithBool:YES]];

or use a C-array, depending on your needs:

BOOL array[100];
array[31] = YES;
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
8

Like Georg said, use a C-array.

BOOL myArray[10];

for (int i = 0; i < 10; i++){
  myArray[i] = NO;
}

if (myArray[2]){
   //do things;
}

Martijn, "myArray" is the name you use, "array" in georg's example.

Nicki
  • 984
  • 8
  • 7
5

From XCode 4.4 you can use Objective-C literals.

[updated_users replaceObjectAtIndex:index withObject:@YES];

Where @YES is equivalent of [NSNumber numberWithBool:YES]

Ivan Marinov
  • 2,737
  • 1
  • 25
  • 17
1

If your collection is large or you want it to be faster than objc objects, try the CFBitVector/CFMutableBitVector types found in CoreFoundation. It's one of the CF-Collections types which does not ship with a NS counterpart, but it can be wrapped in an objc class quickly, if desired.

justin
  • 104,054
  • 14
  • 179
  • 226