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

可紊 提交于 2019-12-25 02:38:37

问题


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


回答1:


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.




回答2:


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.




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/4050007/objective-c-what-is-the-best-way-to-create-and-use-a-dynamic-boolean-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!