What you probably want (unless you're using a very old OS and compiler) is to just use property syntax. I.e.:
@interface MyClass : NSObject
// method declarations here ...
@property (copy) NSString* myVar;
// ... or here.
@end
This will do what you intended to do. This will implicitly synthesize an instance variable and a getter/setter pair for this variable. If you manually wanted to create the instance variable (you generally don't need that unless you need your code to work on very old MacOS versions), this is what the above code does under the hood to create the ivar:
@interface MyClass : NSObject
{
NSString* _myVar;
}
// method declarations here.
@end
Note the curly braces, which tell the compiler that this is not just a global variable somewhere in between the methods, but actually an instance variable that belongs to this object.
If you are creating the property only for internal use and don't want clients of your class to mess with it, you can hide this away a little bit in everything but the oldest ObjC compilers by using a class extension which "continues" the class declaration from the header, but can be placed separate from it (so usually in your implementation file). A class extension looks like a category without a name:
@interface MyClass ()
@property (copy) NSString* myVar;
@end
And you can either put your property declaration in there, or even ivar declarations (again wrapped in curly brackets). You can even declare the same property as readonly
in the class interface, and then re-declare it identical, but as readwrite
in the extension, so that clients only read it, but your code can change it.
Note that, if you didn't use ARC (that is, you've switched off the default of Automatic Reference Counting), you would have to set all your properties to nil
in your dealloc
method (unless they're set to weak
or assign
of course).
NB - All the above are @interface
sections. Your actual code will go in separate @implementation
sections. This is so you can have header files (.h
) you can hand off to your class's clients that just contain the portions you intend them to use, and hide away implementation details in the implementation file (.m
) where you can change them without having to worry someone might have accidentally used them and you'll break other code.
PS - Note that NSStrings
and other objects that you want the immutable flavor of, but that also exist in a mutable flavor (i.e. NSMutableString
) should always be copy
properties, because that will turn an NSMutableString into an NSString so that nobody on the outside can change the mutable string underneath you. For all other object types, you generally use strong
(or retain
if not ARC). For your class's owner (e.g. its delegate) you usually use weak
(or assign
if not ARC).