Search code examples
iphoneinitdeallocivar

ivar check if it has been initialized and used


let's say I have an instance variable MyObject* test;

@property(nonatomic, retain) MyObject* test;

.m

@synthesize test;

I might initialize it or might now depending if I need to. If I don't need it, no point wasting on initialization.

The question is in the dealloc, is it safe to do the following check and release?

-(void) dealloc
{
  if ( test != nil )
  {
   [test release];
  }
{

Thanks!


Solution

  • that's perfectly fine. it is also more idiomatic to simply omit the test for nil.

    behind the scenes, the compiler (typically*) generates a call to objc_msgSend or one of its variants. the implementation of objc_msgSend (and variants) allows the object you message to be nil, in the sense that it is well defined and not considered a programmer error to message nil. the return value of objc_msgSend+ variants is zeroed:

    example:

    NSString * string = nil;
    NSString * copy = [string copy]; << copy will be 0/nil
    NSUInteger length = [copy length]; << length will be 0
    

    this means you must test for nil if returning a c++ object -- the constructor will not be invoked if the receiver is nil.

    *typically, in the sense that there is a handful of c functions the compiler calls to perform messaging as well as some other common routines.