2

In thread "How I managed memory", the author said "I don’t use the full form in init and dealloc, though, because it might trigger KVO or have other side effects." I didn't understand what you mean ?

Source here http://inessential.com/2010/06/28/how_i_manage_memory

DungProton
  • 231
  • 3
  • 7

2 Answers2

1

I think the author should be more careful with the naming conventions.

@property (nonatomic, retain) NSString *something;

should synthesize to

@synthesize something = _something;

This way you can refer to self.something to use the accessor method or _something to use the ivar that backs that property. It's less error prone.

And regarding your question. When you have an accessor you are probably doing something else besides setting that property (like notifying another object or updating the UI) in that accessor method. And you probably don't want to do that on init or dealloc. That's why you may want to access the ivar directly instead, that's not always the case, though.

Odrakir
  • 4,206
  • 1
  • 18
  • 51
0

He is referring to accessing your @properties via the self notation. When synthesizing a property, the getters and setters for that variable are automatically created for you:

@property (nonatomic,strong) MyClass myVar;

@synthesize myVar = _myVar;

- (MyVar *)myVar
{
   return _myVar;
}

- (void)setMyVar:(MyClass *)myVar
{
  _myVar = myVar;
}

These methods are created for behind the scenes when a property is defined and/or synthesized (depending on Xcode version)

so when you do

self.myVar = 5;

You are actually doing [self setMyVar:5];

However, it is possible to directly access the variables and bypass the setter by using the following notation

_myVar = 5;

Example:

@property (nonatomic,strong) MyClass myVar;

@synthesize myVar = _myVar;


 - (void)someMethod
{
    // All do the same thing
    self.myVar = 5;
    [self setMyVar:5];
    _myVar = 5;
}

The author of the article is recommending that you do not use getters and setters within the dealloc and init methods, but directly access the variable using the _myVar notation.

See this answer for further information regarding best practices, etc, but it is a debatable issue: Why shouldn't I use Objective C 2.0 accessors in init/dealloc?

Community
  • 1
  • 1
Tim
  • 8,206
  • 3
  • 40
  • 64
  • 2
    This does not explain *why* using property accessors in init/dealloc might be problematic (which is what the OP asked). – Martin R Apr 11 '13 at 12:12
  • That's a subjective question though, so providing more background may help. – Tim Apr 11 '13 at 12:33