Unnecessary temporary variables when setting property values?

I’m following the book on iPhone development, and there is a certain model that I see in the code example, which does not really matter to me. Whenever a property is set, they first assign a pointer to a new value for the property, then set the property to a pointer, and then release the pointer. Example:

Interface:

@interface DoubleComponentPickerViewController : UIViewController {
    NSArray *breadTypes;
}

@property(nonatomic, retain) NSArray *breadTypes;

@end

Class method:

- (void)viewDidLoad {
    NSArray *breadArray = [[NSArray alloc] initWithObjects:@"White", @"Whole Wheat", @"Rye", @"Sourdough", @"Seven Grain", nil];
    self.breadTypes = breadArray;
    [breadArray release];
}

Is there a reason to do this instead of doing the following?

- (void)viewDidLoad {
    self.breadTypes = [[NSArray alloc] initWithObjects:@"White", @"Whole Wheat", @"Rye", @"Sourdough", @"Seven Grain", nil];
}

Thank you for the light that will undoubtedly shed :)

+3
source share
2 answers

Let me try to explain it differently.

, alloc, copy new , , .

viewDidLoad , . , . , , - - , , , - .

, , ( *). - self.breadTypes. self.breadTypes , ( ). breadArray. , . , . viewDidLoad . , self.breadTypes , , , , breadArray.

, , -, - ( * ).

breadArray. alloc , , self.breadTypes :

self.breadTypes = [[[NSArray alloc] initWithObjects:@"White", ..., nil] release];

, , self.breadTypes, , breadArray.

, :

- (void)viewDidLoad {
    self.breadTypes = [[NSArray alloc] initWithObjects:@"White", @..., nil];
    [self.breadTypes release];
}

, (self.breadTypes getter), , temp.

* , , autorelease :

- (void)viewDidLoad {
    self.breadTypes = [[[NSArray alloc] initWithObjects:@"White", ..., nil] 
                        autorelease];
}

Apple , autorelease vs. release. . , , . , , viewDidLoad. ( iPhone, MacOS X Cocoa), .

BTW: retain , , , release , .

+9

. , . , retain, , @synthesize breadTypes;, setBreadTypes, breadType . , it alloc 'ed.

, , :

- (void)viewDidLoad {
    self.breadTypes = [[[NSArray alloc] initWithObjects:@"White",
                              @"Whole Wheat", @"Rye", @"Sourdough",
                              @"Seven Grain", nil] 
                        autorelease];
}

Cocoa

+3

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


All Articles