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.
I need to create an instance variable of type BOOL with a default value
Share
Assuming you are using the current Xcode, you can declare the ivar in the implementation like this:
Historically, you had to declare instance variables in the
@interfacebecause of the way classes were implemented. This is now necessary only if you are targeting 32 bit OS X.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).
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
Note that, although the compiler will produce warnings for the above, at run time, any class can send
setMyBool:ormyBoolto objects ofMyClass.