Here's the easiest thing. Ready to have your mind blown with how simple this can really be?
The following code demonstrates how to share a data object between two view controllers:
VCOne.h
@interface VCOne : UIViewController {
NSString *mystring;
}
@property (nonatomic, retain) NSString *mystring;
@end
VCOne.m
@implementation VCOne
@syntheize mystring;
-(void)viewDidLoad {
//you probably wouldn't do it here, but just so it has a
//place to live, I'm doing it in viewDidLoad...
VCTwo *two = [[VCTwo alloc] initWithNibName:@"VCTwoView" bundle:nil];
two.mystring = self.mystring;
[self.navigationController pushViewController:two animated:YES];
[two release];
}
-(void)dealloc {
[mystring release];
[super dealloc];
}
VCTwo.h:
@interface VCTwo : UIViewController {
NSString *mystring;
}
//nb the "assign" in the following line where you're probably
//used to seeing "retain"!!
@property (nonatomic, assign) NSString *mystring;
@end
VCTwo.m:
@implementation VCTwo
@synthesize mystring;
-(void)viewDidLoad {
self.mystring = @"I set this string inside VCTwo!";
}
-(void)dealloc {
[super dealloc];
}
Okay, so! One view controller has a NSString called *mystring and declares it as a @property with the retain
setter semantics. The second one has a NSString called *mystring and declares it as a @property with the assign
setter semantic (and, importantly, DOESN'T release it in -(void)dealloc
. This is memory-safe, although it does depend on the previous VC not releasing the object away from the current one!).
Then when the first VC instantiates the second one, it assigns its mystring field to the new VC's field. The new VC accepts that object and assigns it on its own @property
. Now anything you do to that variable in VCTwo is ALSO happening on the value that's referred to in VCOne. They're literally sharing that pointer now. Both view controllers have a handle on the same piece of memory.
Why not use retain
inside VCTwo? Because the setter method that's synthesized when you say retain
clears and resets the variable when it is set. They become separate objects, and they're not actually synced up. You can pass values between view controllers that way, but not references.
If you find yourself having issues with the object going away because it's getting released upstream (as a result of memory warnings, perhaps), you can always explicitly call [mystring retain]
and keep it around. Just be sure you DO release it in -(void)dealloc
if you do that.