Search code examples
iphonememory-managementnsmutablearrayassignretain

NSMutable array - assign and retain objects


I need some info about how to assign, retain objects.

For example - if we have two viewcontrollers and needed to pass an array data from viewcontrlr 1 to viewContrl 2, how can we send the object from view 1 to view 2 and release it in view 1 and retain it in view 2.

A simple = operator is just assigning the address which again points to view 1 object. What is the best way so we can release obj in view 1 and retain a new object in view 2 when passed from view 1.


Solution

  • Create a NSMutableArray in your view controller 2 and declare a retain property for it.

    @interface VC2 : UIViewController
    {
       NSMutableArray *mutableArrayInVC2
    } 
    @property (nonatomic, retain) NSMutableArray *mutableArrayInVC2
    

    Then in your view controller one you can pass it with:

    viewController2Instance.mutableArrayInVC2 = mutableArrayInVC1
    

    And it's safe to release it with:

    [mutableArrayInVC1 release];
    

    [EDIT TO ADDRESS YOUR COMMENT]

    When you declare a retain property for your mutableArrayInVC2 and pass mutableArrayInVC1 to it, "behind the scenes" you are accessing the variable via its setter method as per below:

    -(void)setMutableArrayInVC2:(NSMutableArray *)arrayValue
    {
        [arrayValue retain]; // This is your mutableArrayInVC1
        [mutableArrayInVC2 release]; // This is nil the first time you access it which is cool - we can send messages to nil in ObjC
        mutableArrayInVC2 = arrayValue; // So basically you end up doing and assignment but only after retaining the object so it is pointing to the same memory address BUT it is now 'owned' by your VC2 instance.
    }
    

    Hope it makes sense! Rog