jhon
jhon

Reputation: 15

custom class = custom +alloc , custom +init

I'm new with objective c for the iphone.

I'm writing a custom class, then, should I write my own +alloc, +init methods? I believe that: the +alloc will just call [thing alloc]; and the +init will perform something like: [thing setValue:X];

is there a "default" +alloc and +init methods? if yes, what should I wait for the default +alloc and +init?, let's say i have a NSMutableDictionary* i.e.

@interface class1 : NSObject {

    NSString *test; 
    NSMutableDictionary *map;
}

thanks

Upvotes: 0

Views: 1749

Answers (2)

David Gelhar
David Gelhar

Reputation: 27900

You generally don't need to write your own +alloc method.

For your example, you might have an -init that looks like:

- (id)init {
    self = [super init];
    if (self) {
        map = [[NSMutableDictionary dictionary] retain];
    }
    return self;
}

Note that you first call the superclass -init, and check that it worked, before initializing your own variables.

Upvotes: 5

Jacob Relkin
Jacob Relkin

Reputation: 163228

You should NEVER override alloc.

As for init, which is an instance method, by the way, yes that would be the place where you'd probably want to set up your variables.

Upvotes: 2

Related Questions