Returning other objects in init

I read in many places that you should always initialize Objective-C objects:

- (id) init {
    if (self = [super init]) {
        ....
    }
    return self;
}

Because the super method initcan return a single object from the current one self.

Now I'm trying to do something like this, and I'm not sure if I mean correctly how to save and free the work:

- (id) init:(int)idx {
    id obj = [Cache findSelf:idx];
    if (obj) {
        [self release];
        self = [obj retain];
    } else {
        self = [self doLoad];
    }
    return self;
}

I am most curious if this is the right way to save and release selfand obj. Is there a better way?

+3
source share
2 answers

self = [super init], Cocoa , , . , , . -init, , Objective-C .

-init-, , , -init . , :

+ (id) instanceForIndex:(NSUInteger)index {
    id obj = [Cache findSelf:index];
    if (obj == nil) {
      obj = [[self alloc] init];
      // Add to cache
    }
    return [[object retain] autorelease];
}

-init. -init.

, , Cache, (, NSMutableDictionary, NSNumber, ). SO .

+7

, . , , init , else, , .. self = [super init].

+1

Source: https://habr.com/ru/post/1713464/


All Articles