Correct way to allocate / initialize instance variables in Objective-C?

I was looking at some sample code on a Jeff LaMarche excellent blog when I came across the following:

- (void) applicationDidFinishLaunching: (UIApplication *) application
{
    CGRect rect = [[UIScreen mainScreen] bounds];

    window = [[UIWindow alloc] initWithFrame: rect];

    GLViewController * theController = [[GLViewController alloc] init];
    self.controller = theController;
    [theController release];

    // ...
}

In .h we see that the โ€œwindowโ€ and โ€œcontrollerโ€ are Ivars declared like this:

@interface OpenGLTestAppDelegate: NSObject 
{
    UIWindow * window;
    GLViewController * controller;
}
@property (nonatomic, retain) IBOutlet UIWindow * window;
@property (nonatomic, retain) IBOutlet GLViewController * controller;
@end

My question is: why are the "window" and the "controller" assigned differently?

I think I understand why each type of task works (tracking the number of deductions), but why are they assigned differently? In particular, why the controller is not assigned in the same way as a window with the same line without going through the setter:

    controller = [[GLViewController alloc] init];

In general, when will you use the single line method and when will you use the multiple line method?

Thanks.

+3
source share
3 answers

Does it create a custom parameter for the instance variable controller?

, , , controller . controller :

controller = [[GLViewController alloc] init];

setter; , , :

self.controller = theController;

setter, :

[self setController:theController];

. , .

Edit:

, , , , - , .

, , , setter , release . ,

[[self controller] release]

, setter , , โ€‹โ€‹ , release retain, .

+3

, , , ( setter). (GLView.m) -setController ivar , () -setupView:.

, , :

self.controller = [[[GLViewController alloc] init] autorelease];

( ):

[self setController:[[[GLViewController alloc] init] autorelease]];

, - setter.

(. .)


Edit:

. "GLViewController * controller" ivar ___PROJECTNAMEASIDENTIFIER___AppDelegate.m, GLView.m, . ( , . 77-81 , , - AppDelegate .)

GLViewController, . , , keep-release, , . , . - .

+2

, ivar autorelease. - , -, . Apple iPhone. , setter.

, ( window ivar), setter ( controller ivar), , .

ivar:

  • ivar. setter ivars, .
  • setter ivars.

, . - , , , .

: / Objective C.

+2

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


All Articles