23

How to use a boolean property in objective C class, i did it like:

@property (nonatomic, copy) BOOL *locationUseBool;

but it gives error that:

Property with 'copy' attribute must be of object type.

what is the correct way of declaring?

Firdous
  • 4,624
  • 13
  • 41
  • 80

3 Answers3

28

You can declare this way also.

@property (assign) BOOL locationUseBool;

Basically, if you say nonatomic, and you generate the accessors using @synthesize, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects

In a multi-threaded program, an atomic operation cannot be interrupted partially through, whereas nonatomic operations can.

Mayank Jain
  • 5,663
  • 7
  • 32
  • 65
Kamleshwar
  • 2,967
  • 1
  • 25
  • 27
25
@property (nonatomic, assign) BOOL locationUseBool;

No asterisk, no copy, no retain.

bneely
  • 9,083
  • 4
  • 38
  • 46
  • 1
    Or you can omit the second parameter altogether (defaulting to assign). – Alexander Feb 22 '12 at 10:46
  • Also consider using the official C99 `bool` type. It has better behaviour when casting etc. – JeremyP Feb 22 '12 at 11:51
  • 1
    @JeremyP when casting to what? `BOOL` is recommended by everything I've ever read on Obj-C. What am I missing? – Dan Rosenstark Feb 23 '12 at 06:45
  • 4
    @Yar: `BOOL` is just a typedef for `char`. `bool` is a proper boolean type that is logically 1 bit wide. In C, any number of integer type that is not 0 is meant to evaluate to true. However casting any non zero integer whose lower 8 bits happen to be zero to `BOOL` will result in a BOOL variable that is false. `(BOOL)0x1000` is false but `(bool) 0x1000` is true. – JeremyP Feb 23 '12 at 09:45
  • @JeremyP I'm shocked! http://pastie.org/3438141 So, um, should I be using `bool` for everything everywhere, like properties, etc.? Admittedly, I'm not assigning `ints` to BOOLs much, but what's the cost-benefit? – Dan Rosenstark Feb 23 '12 at 16:09
  • @Yar: I use standard C99 types everywhere except where a Foundation or Cocoa API specifies one of the Foundation types. And in respect of booleans, I always do something like `(x ? YES : NO)` rather than rely on the cast. – JeremyP Feb 24 '12 at 11:00
  • Please see: http://stackoverflow.com/questions/9433121/implications-of-int-values-not-fitting-bool-or-bool-for-objective-c where I expand this into a full thinger... Thanks! – Dan Rosenstark Feb 24 '12 at 16:19
1

This one worked for me.

@property (nonatomic) BOOL locationUseBool;

There is not asterisk * symbol in property declaration. Also, use of 'assign' is optional.

Jayprakash Dubey
  • 35,723
  • 18
  • 170
  • 177