What is the idiomatic way of managing reference counts during Obj-C initializers?

I am learning Objective-C. In my first non-trivial project, I came across the question of how to better handle the resources passed to the initializer compared to the default initializer. My class has a saved resource enginethat can be set manually after creation either during initialization explicitly or during default initialization:

- (id)init {
    if ((self = [super init])) {
        id e = [[XorShiftEngine alloc] init];
        [self setEngine: e];
        [e release];
    }
    return self;
}

- (id)initWithEngine:(NSObject <RandEngine> *)e {
    if ((self = [super init]))
        [self setEngine: e];
    return self;
}

- (id)setEngine:(NSObject <RandEngine> *)newEngine {
    [newEngine retain];
    [engine release];
    engine = newEngine;
    // Some other stuff which needs to happen on changing the engine.
    return engine;
}

The default initializer, in particular, seems very ugly to me, alternating the code related to itself, then the member, then I again, then the member again and calling the object only to release it later. It also violates the designated idiom of the initializer.

, ?

+3
3
- (id)init {
    id e = [[XorShiftEngine alloc] init];
    self = [self initWithEngine: e];
    [e release];
    return self;
}

// designated initializer
- (id)initWithEngine:(NSObject <RandEngine> *)e {
    self = [super init];
    if (self != nil) {
        engine = [e retain];
        // engine initialization stuff
    }
    return self;
}

- (id)setEngine:(NSObject <RandEngine> *)newEngine {
    [newEngine retain];
    [engine release];
    engine = newEngine;
    // Some other stuff which needs to happen on changing the engine.
    return engine;
}

. , , - , init.

Apple /getters init dealloc ( , ).

, , , .

+2
- init
{
    self = [super init];
    if (self != nil) {
        // initialization here
    }
    return self;
}

" ", :

- initWithBob:(Bob*)aBob
{
   self = [self init];
   if ( self != nil ) {
       ... deal with aBob here ...
   }
   return self;
}

, . . .

.. initWithBob:, @property(retain) Bob* bob;, init . - .


, Car, - :

@interface Car:NSObject
+ car;
+ carWithEngine:(Engine*)anEngine;
- initWithEngine:(Engine*)anEngine;
@end

; car alloc/initWithEngine:/autorelease.

, .

+3

e -init? ... , , . . , -init nil -initWithEngine: -initWithEngine: , .

" " , " ". - , - . -initWithEngine: - .

+3

All Articles