Objective-C中的BOOL问题 [英] BOOL issue in Objective-C
问题描述
当我试图从字典中获取BOOL时,我得到:
When I'm trying to do this to get the BOOL from a dictionary, I get:
BOOL isTrue = [someDict objectForKey: @"isTrue"];
我得到:
Initialization makes integer from pointer without a cast
我这样做是为了设置字典:
I set the dictionary by doing this:
self.someDict = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:
self.isTrue, @"isTrue",
nil];
有什么想法吗?
推荐答案
使用:
BOOL isTrue = [[someDict objectForKey:@"isTrue"] boolValue];
将BOOL
存储在NSDictionary
中的唯一方法是将其包装在NSNumber
对象中. BOOL
是原始的,字典仅包含对象.
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.
类似地,要在字典中存储BOOL
,请使用:
Similarly, to store a BOOL
in a dictionary, use:
[someDict setObject:[NSNumber numberWithBool:isTrue] forKey:@"isTrue"];
(回应评论)
有两种方法可以将其表示为@property
.一种是将ivar声明为BOOL
,另一种是将其声明为NSNumber
.
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
.
对于第一种情况,其ivar为:BOOL isTrue;
,而属性为@property BOOL isTrue;
(显然,我忽略了命名约定).
For the first case, the ivar is: BOOL isTrue;
, and the property is @property BOOL isTrue;
(I'm ignoring naming conventions, obviously).
对于NSNumber
,其ivar为:NSNumber * isTrue;
,而属性为@property (nonatomic, retain) NSNumber * isTrue;
.如果采用这种方法,则可能需要提供第二种设置方法(setIsTrueBool
或其他方法),该方法可以让您只传入YES
或NO
,然后自己进行装箱.否则,任何打电话给它的人都必须自己做拳击.
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.
我个人最有可能选择选项#1,但这实际上取决于课程的目的.
I'd personally most likely go with option #1, but it really depends on what the class's purpose was.
这篇关于Objective-C中的BOOL问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!