Macro- lValue error

Discussion in 'iPhone/iPad Programming' started by mpramodjain, Jun 4, 2011.

  1. macrumors regular

    Joined:
    Nov 20, 2008
    Location:
    Banglore
    #1
    Hi,

    I have been using, the following macro, for releasing the objects

    #define RELEASE_NIL(object) if(nil!=object){[object release]; object=nil; }

    But when I use this macro for releasing a class object(SubClass of NSObject), following are my responses..



    RELEASE_NIL(mAppDelegate_.myObject); - No Error
    RELEASE_NIL([mAppDelegate_ myObject]); - error: lvalue required as left operand of assignment

    Do anyone know, whats the problem with the second way throwing error and what it is expecting..????
     
  2. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    Macros work a simple text replacement. So in the second case you get

    Code:
    if(nil!=[mAppDelegate_ myObject]){[[mAppDelegate_ myObject] release]; [mAppDelegate_ myObject]=nil;
    
    The final statement is clearly illegal. You cannot set the value in this way. The reason it works in the first case is down to the way the syntactic sugar of properties works. Properties are basically a clever/case sensitive text expansion to the getter/setter methods. The first case, after macro expansion looks like:

    Code:
    if(nil!=mAppDelegate_.myObject){[mAppDelegate_.myObject release]; mAppDelegate_.myObject=nil;
    
    After the syntactic sugar of the properties is expanded we get:

    Code:
    if(nil!=[mAppDelegate_ myObject]){[[mAppDelegate_ myObject] release]; [mAppDelegate_ setMyObject:nil];
    
    Note how the replacement is clever: it knows when to use the set accessor. This is the key difference.

    I would note that releasing an object owned by another class in this way is in contravention of the normal Cocoa memory management rules and I would recommend against it.
     
  3. thread starter macrumors regular

    Joined:
    Nov 20, 2008
    Location:
    Banglore
    #3

    Thanks for the reply. It was my insane, not to think any long on this.

    Can you please make it more clear, how it is contravention of the normal Cocoa memory management, as per my little knowledge, the preprocessor just replaces the passed argument..
     
  4. Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    You should have read, and understood, all of The Cocoa Memory Management Guide before writing any code, in particular the Memory Management Rules. These state

    You are not taking ownership of the object but you are releasing it.
     

Share This Page