The best way to handle saving properties

If you have an object with a property that has a fixed setter, which one works best?

1

-(id)init {
    if((self = [super init])) {
        self->_retainingProperty = [[NSObject alloc] init];
    }
    return self;
}

2

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

3

-(id)init {
    if((self = [super init])) {
        NSObject *obj = [[NSObject alloc] init];
        self.retainingProperty = obj;
        [obj release];
    }
    return self;
}

All will be associated with the release of dealloc

Perhaps there is another way that I skipped.

+3
source share
3 answers

I usually do:

- (id ) init
{
   self = [super init];

   if ( self )
   {
      retainingProperty = [[NSObject alloc] init];
   }

   return self;
}

I would not suggest # 2 or # 3 if you do not know that they can refer to KVO things that you are not planning.

+4
source

All of the above is well and broadly equivalent. You can also access a member variable using only its name:

-(id)init {
    if((self = [super init])) {
          _retainingProperty = [[NSObject alloc] init];
    }
    return self;
}

- , , / , , , .

- setter, , , set set. , , , , . - , .

+1

spring. ivar:

- (id) init
{
    if ( self = [super init] )
    {
        _retainingProperty = [[NSObject alloc] init];
    }
    return self;
}

:

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

, .

ivar. init, , , .

Similar considerations apply in dealloc, btw: it is better to use releaseyour ivars rather than using property accessors.

+1
source

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


All Articles