Why do they initialize pointers this way?

In almost all the books that I read, and the examples that I look through, I see that pointers are initialized in this way. Let's say that I have a class variable NSString * myString that I want to initialize. I almost always see how this is done:

-(id)init {
    if (self = [super init]) {
        NSString *tempString = [[NSString alloc] init];
        self.myString = tempString;
        [tempString release];
    }
    return self;
}

Why can't I just do the following?

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

I don’t understand why an extra tempString is required in the first place , but I might miss something with memory management. Is there a way I want to do something acceptable or will it cause some kind of leak? I read the memory management guide on developer.apple.com, and if I just don’t miss something, I don’t see the difference.

+3
2

self.myString ,

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

. , , autorelease.

+5

.

, myString ivar, , myString ( ). self.myString, .

+4

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


All Articles