iphaaw
iphaaw

Reputation: 7204

Objective C: What is the best way to create and use a dynamic boolean array?

I have been struggling with the best way of creating, accessing and updating values from a dynamic boolean array for more than a week now.

@interface myDelegate : NSObject
{
   NSMutableArray *aShowNote;
}
@property (nonatomic, copy) NSMutableArray *aShowNote;

This is how I have initialised my array:

NSMutableArray *aShow = [[NSMutableArray alloc] init]; 
for (i=0; i < c; i++) 
    [aShow addObject:[NSNumber numberWithBool:false]];
self.aShowNote = aShow;

This seems to work OK but I'm baffled why each element is initialised with the same address.

But then what I've discovered in my research so far is that is seems that you need to replace the object if you want to change its value:

myDelegate *appDelegate = (myDelegate *)[[UIApplication sharedApplication] delegate];
NSInteger recordIndex = 1;

NSNumber *myBoolNo = [appDelegate.aShowNote objectAtIndex:recordIndex];
BOOL showNote = ![myBoolNo boolValue];

[appDelegate.aShowNote replaceObjectAtIndex:recordIndex withObject:[NSNumber numberWithBool:showNote]];

but this approach just seems to be over complicated (and it crashes too).

Terminating app due to uncaught exception'NSInvalidArgumentException', reason: '-[__NSArrayI replaceObjectAtIndex:withObject:]: unrecognized selector sent to instance 0x5b51d00

Any pointers to improve this code (and of course to make it work) would be very gratefully received.

Thanks

Iphaaw

Upvotes: 0

Views: 2603

Answers (4)

mouviciel
mouviciel

Reputation: 67831

Why not use plain C for this simple case?

BOOL *aShow = malloc(sizeof(BOOL)*c);
for (i=0 ; i<c ; i++)
    aShow[i] = false;

You just have to remember to free(aShow) when you are done with it.

Upvotes: 2

Beno&#238;t
Beno&#238;t

Reputation: 7427

It is not possible to change value of a NSNumber. It not mutable class.
Then, when you ask for two same value, the same object is return.

In your array init, why you don't initialized directly the array to avoid copy problem:

aShowNote  = [[NSMutableArray alloc] init]; 
for (i=0; i < c; i++) {
    [aShowNote addObject:[NSNumber numberWithBool:false]];
}

Upvotes: 1

JeremyP
JeremyP

Reputation: 86651

I'm baffled why each element is initialised with the same address.

Why? NSNumbers are immutable. The runtime only needs one NSNumber object to represent FALSE.

Upvotes: 0

Matthias Bauch
Matthias Bauch

Reputation: 90117

the problem is that copy in a property copies the assigned object. And copy creates immutable objects.

Change your property to read: @property (nonatomic, retain) NSMutableArray *aShowNote;


And I think there is not much to improve, from what I know this is the way to go if you want an NSArray with booleans.

Upvotes: 3

Related Questions