Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? I've seen people define it in their .h file but I don't really need this variable to be public. Thus shouldn't I put it in my .m file? Additionally, should I make it a property? Or should I ever not make something a property? Thanks.

like image 298
Nosrettap Avatar asked May 21 '12 12:05

Nosrettap


1 Answers

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.

like image 104
JeremyP Avatar answered Sep 28 '22 11:09

JeremyP