3

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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Exactly. I'll add you also need to put @synthesize mutableArrayInVC2 in your VC2.m file...
All good, small doubt- so when we create Mutable array in VC1 I use alloc init method to create the instance (I do have synthesize, nonatomic, retain all in place in VC1 and VC2). so when we assign like you said (viewController2Instance.mutableArrayInVC2 = mutableArrayInVC1)) dont we need the alloc and init method before we actually assign a NSMutable Array to VC2?
Great question! You don't and I have edited my answer to try and explain why - see if it makes sense...
0

Also, you may want to check out this article for info on retain count mechanisms in general. It's very similar to what's in Cocoa Programming for Mac OS X which IMO is one of the best intro books on Cocoa and Obj-C in general. I'm not sure how much experience you have with Obj-C/Cocoa but if you're looking for that kind of intro it's a great place to start.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.