开发者

custom class = custom +alloc , custom +init

开发者 https://www.devze.com 2023-01-09 06:48 出处:网络
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'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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号