开发者

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开发者_JAVA技巧 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


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.


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.


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]];
}


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜