Resolved ARC, @property, alloc/init

Discussion in 'iOS Programming' started by larswik, Aug 24, 2013.

  1. larswik, Aug 24, 2013
    Last edited: Aug 25, 2013

    larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    Hey, quick question that I am not 100% sure about. I am using ARC to release my objects automatically. If I have an @property do I still need to alloc/ init an object?

    Example
    Code:
    @property (nonatomic, retain) NSMutableDictionary *charDict;
    @synthesize charDict;
    
    charDict = [NSMutableDictionary alloc]init];
    
    Since I set up retain in the @properties the object should be retained. So if I alloc/init the dict it feels like I am adding another retain count to it even though ARC handles the release of the object.
     
  2. Duncan C macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #2
    A property is just a pointer that can contain an object. Until you allocate an object and store it there, the property is nil.

    So yes, you must still alloc/init in ARC.

    ARC takes care of object ownership for you. Before ARC, you had to worry about whether a method call gave you an owning reference (retained) to an object, or a non-owning (autoreleased) reference. For owning references, you had to make sure you sent the object a release/autorelease when you were done with it.

    With ARC, the system takes care of tracking object ownership for you. As soon as the last owning reference to an object goes out of scope, or is set to nil, the object is released.
     
  3. CodeBreaker macrumors 6502

    Joined:
    Nov 5, 2010
    Location:
    Sea of Tranquility
    #3
    Also, use strong and weak in place of retain and assign for ARC.
     
  4. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #4
    And by containing an object this means that I do not also need to declare my iVar?

    Just sudo code,
    Code:
    @interface WelcomeVC :NSObject{
    
        [COLOR="Red"]SomeClass *object;[/COLOR]
    }
    @property(strong) SomeClass *object;
    
    @implementation WelcomeVC
    @synthesize object:
    
    -(void)xyz{
       object = [[SomeClass alloc]init];
    }
    
    -
    
    Am I able to just declare my iVars at the property line of code instead of between the brackets in the header, {my iVars}? The code above is redundant with the same iVar declared twice, right?
     
  5. Duncan C macrumors 6502a

    Duncan C

    Joined:
    Jan 21, 2008
    Location:
    Northern Virginia
    #5

    Right.

    That's a fairly recent change. Apple extended Objective C so that properties now auatomatically define an iVar to go with each property. By default, the iVar that backs a property has the same name as the property but a "_" prefix.

    You also no longer need the @synthesize statement.
     
  6. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006

Share This Page