Curnelious
Curnelious

Reputation: 1

Understanding boolean property

Using Xcode5 with ARC , I am creating a property for a boolean :

@property (nonatomic) BOOL done;

than I am using it with self.done .

Problem is that sometimes I get error when using it like that. for example(error) :

//implicit conversion of bool to id disallowed in-ARC
[encoder encodeObject:self.done forKey:@"text"];

With this situation I have two questions: 1. When and why should I create a property with BOOL, and what is the logic behind this? 2. Why I am getting this error ?

Upvotes: 0

Views: 99

Answers (2)

Tiago Almeida
Tiago Almeida

Reputation: 14237

Question 2

You are getting that error because BOOL is a primitive type and the encoder expects an Object. You can easily solve that wrapping your bool with a literal, like this

[encoder encodeObject:@(self.done) forKey:@"text"]

This basically convertes to:

[encoder encodeObject:[NSNumber numberWithBool:self.done] forKey:@"text"]

Question 1

You can create a property with BOOL because it is more direct that a NSNumber initiated with a BOOL. For instance, if you wanted to do ifs on that bool with a NSNumber you would need to do number.boolValue all the time.

The advantage of declaring a property vs declaring an iVar is that it gives you a KVO ready structure and you have an entry point to get the value and an entry point to set the value. In the case of the BOOL this is mainly useful for debugging. Although KVO is also a plus :) (If you need more info on properties vs iVars follow my answer on SO)

Upvotes: 3

Anoop Vaidya
Anoop Vaidya

Reputation: 46533

As you see encodeObject: in

[encoder encodeObject:self.done forKey:@"text"]; 

but done is not an Objective-C object. Rather it is an BOOL.

BOOL is typedef signed char BOOL;

You cant box the BOOL type to Obj-C object as NSNumber and encode it.

[encoder encodeObject:@(self.done) forKey:@"text"]; 

Upvotes: 1

Related Questions