1

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.

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

You should read - The Objective-C Programming Language: Allocating and Initializing Objects

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.