0

As I know, I can use global variable transfer the value among the multi viewcontrollers of a project.

But I hope to know the best way to transfer NSString variables between multi viewcontrollers and the way to avoid memory leak.

Welcome any comment

Thanks

interdev

arachide
  • 8,006
  • 18
  • 71
  • 134

1 Answers1

1

The best way to pass parameters between your view controllers is to use properties. If applicable, have your app delegate set the initial value in your root view controller. Then you set the property before you push a new view controller on your navigation stack, or raise a new view controller modally. e.g.:

MyViewController* myViewController = [[MyViewController alloc] initWithNibName:@"MyView" bundle:nil];
myViewController. someStringVariable = someStringVariable;
[self.navigationController pushViewController: myViewController animated:YES];
[myViewController release];

When passing NSString objects, you will normally want to use copy instead of retain when declaring the property. (See this previous SO question for more detail.) e.g.:

@interface MyViewController : UIViewController
{
    NSString* someStringVariable;
}

@property (nonatomic, copy) NSString* someStringVariable;

@end

Avoid leaking memory by releasing the property in the view controller's dealloc method, e.g.:

- (void)dealloc
{
    [someStringVariable release];
    [super dealloc];
}
Community
  • 1
  • 1
Shaggy Frog
  • 27,575
  • 16
  • 91
  • 128