How do I initialize an instance variable when the object is created in Objective C?
In C++ I would do this in the constructor, but on Objective C开发者_如何学运维 I do not know how I am supposed to initialize it.
For example I have a member variable that has to be a dictionary and I want to initialize this dictionary.
When you say initialize the dictionary, I am assuming you just want to allocate memory for it. If so you can do the following sample:
- (id) init {
self = [super init];
if (self != nil) {
_privateDict = [[NSMutableDictionary alloc] initWithCapacity:40];
}
return self;
}
Generally, you use the init
method. For example:
Myclass *anInstance = [[MyClass alloc] init];
Some classes have specialized initializers that will take parameters. A classic example is any UIViewController subclass that you implement. Does this look familiar?
MyUIViewController *viewController = [[MyUIViewController alloc] initWithNibNamed: @"MyUIViewController" bundle: nil];
Notice the initWithNibNamed
bit. You can write custom initializer like that as well. I suggest reading code that others wrote. Look for the initializer and try to understand how it was written/"set up".
To make a dictionary, you can use NSDictionary
or NSMutableDictionary
. Those have several initializers. You can use initWithObjects:
and then pass in a bunch of objects to store in the dictionary.
You should read - The Objective-C Programming Language: Allocating and Initializing Objects
精彩评论