How do I create a BOOL instance variable in objective c? How do I create a BOOL instance variable in objective c? objective-c objective-c

How do I create a BOOL instance variable in objective c?


I need to create an instance variable of type BOOL with a default value of FALSE in one of my objective c classes. How do I do this?

Assuming you are using the current Xcode, you can declare the ivar in the implementation like this:

@implementation MyClass{@private    BOOL myBool;}

I've seen people define it in their .h file but I don't really need this variable to be public.

Historically, you had to declare instance variables in the @interface because of the way classes were implemented. This is now necessary only if you are targeting 32 bit OS X.

Additionally, should I make it a property?

That depends. You should definitely make it a property if it is part of your class's external API (for unrelated classes or subclasses to use. If it's only part of the object's internal state, you don't need to make it a property (and I don't).

Or should I ever not make something a property? Thanks.

If you are not using ARC and the type is an object type (BOOL is not) you should always make it a property to take advantage of the memory management of the synthesized accessors. If you are using ARC, the advice on the Apple developer list is to make stuff that is part of the API properties and stuff that is internal state as ivars.

Note that, even for internal state, you might want to use KVO, in which case, use a property.

If you declare this BOOL as a property and synthesize it, you do not need to explicitly declare the ivar. If you want to make the property "visible" only to the class itself, use a class extension

@interface MyClass()@property (assign) BOOL myBool;@end@implementation MyClass@synthesize myBool = myBool_;  // creates an ivar myBool_ to back the property myBool.@end

Note that, although the compiler will produce warnings for the above, at run time, any class can send setMyBool: or myBool to objects of MyClass.


If you want to make a private variable you can use the power of categories.Make a class MyClass for example and in the .m file do the following:

#import "MyClass.h"@interface MyClass() //This is an empty category on MyClass class@property (nonatomic, assign) BOOL myBool;@end@implementation MyClass@synthesize myBool = _myBool;-(void)myMethod {   self.myBool = YES; //this is using the property   _myBool = NO; //this is the instance variable, as @synthesize creates an instance variable for you   // both are private}@end


BOOL's are declared as iVars with a simple BOOL myBool, and as a property with @property (nonatomic, assign) BOOL myBool. Take note though, BOOLean values are inititalized to NO (nil). If you need a BOOL to be accessible from other classes, or "global" in the m file, use an iVar or a property, otherwise just declare them as scoped vars in an individual method.