开发者

BOOL issue in Objective-C

开发者 https://www.devze.com 2022-12-16 16:24 出处:网络
When I\'m trying to do this to get the BOOL from a dictionary, I get: BOOL isTrue = [someDict objectForKey: @\"isTrue\"];

When I'm trying to do this to get the BOOL from a dictionary, I get:

BOOL isTrue = [someDict objectForKey: @"isTrue"];

I get:

Initialization makes integer from pointer without a cast

I set the dictionary by doing this:

self.someDict = [[NSMutableDictionary alloc]
    initWithObjectsAndKeys:
        self.isTrue, @"isTrue",
        nil];
开发者_StackOverflow

Any ideas?


Use:

BOOL isTrue = [[someDict objectForKey:@"isTrue"] boolValue];

The only way to store a BOOL in an NSDictionary is to box it in an NSNumber object. A BOOL is primitive, and a dictionary only holds objects.

Similarly, to store a BOOL in a dictionary, use:

[someDict setObject:[NSNumber numberWithBool:isTrue] forKey:@"isTrue"];

EDIT: (in response to a comment)

There are two ways of representing this as an @property. One is to declare the ivar as a BOOL, and the other is to declare it as an NSNumber.

For the first case, the ivar is: BOOL isTrue;, and the property is @property BOOL isTrue; (I'm ignoring naming conventions, obviously).

For the NSNumber, the ivar is: NSNumber * isTrue; and the property is @property (nonatomic, retain) NSNumber * isTrue;. If you go with this route, you might want to provide a second setter method (setIsTrueBool or something) that allows you to just pass in YES or NO, and then you do the boxing yourself. Otherwise anyone who calls this would have to do the boxing themselves.

I'd personally most likely go with option #1, but it really depends on what the class's purpose was.

0

精彩评论

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

关注公众号