Greg
Greg

Reputation: 34798

is it OK to retain a variable passed by value in objective-c?

is it OK to retain a variable passed by value in objective-c?

That is say:

Question - So is it OK for this controller 2 variable to be set using "Retain", and also have it "released" and set to nil in the "dealloc" method? that is it won't affect the object for controller 1? What happens for example if controller 2 is deallocated and the "release" and "=nil" is hit, will this affect the object as it's still used by controller 1.

Controller 2 Code extract

@interface SelectorController : UITableViewController {
    Config *_returnObject;
}
@property (nonatomic, retain) Config *returnObject;
@end


// implementation
@synthesize config;  
- (void)dealloc
{
    [config release];               config = nil;
    [super dealloc];
}

Upvotes: 0

Views: 204

Answers (2)

Morten Fast
Morten Fast

Reputation: 6320

Retaining and releasing the variable in controller 2 is more than OK, it's how you should do it. :)

Setting the variable to nil in the controller 2, will only set the variable to nil, not the stuff the variable points to, so your object will still be there for the variable in controller 1 to work with.

Upvotes: 1

Rui Peres
Rui Peres

Reputation: 25917

It depends, its ok for you to retain the variable in View Controller 2. Because each controller will be responsible for theirs variables. If instead, you assign your variable, even if you are using the variable in the second controller, it will be the first controller the responsible.

Upvotes: 1

Related Questions