I have a tabbed views where I need to select various options from different tabbed views which should be appended in the same string. For this I want to use a NSMutableString.
After all the options are selected and string is formed as required. I want to access this NSMutableString in the next view which is not tabbed. I think for this I need to declare the NSMutableString as a global variable?
Can someone please help me with this. I am new to objective-c and xcode. Thank you. Any help is much appreciated!
And probably several others.
You can use NSUserDefaults for this:
To save: (call before next view loaded in previous view class)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:yourString forKey:@"KEYNAMEHERE"];
[defaults synchronize];
To retrieve (call when next view is loaded in the next view's class)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableString *string = [defaults objectForKey:@"KEYNAMEHERE"];
Another option would be to have a singleton object, especially useful if you have more than just one variable you want shared.
Here's a good post about doing singletons right: http://lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html
Basically you'd have write a very simple class something like:
State.h:
@interface State : NSObject
@property (atomic, strong) NSMutableString *mystring;
+ (id)sharedInstance;
@end
State.m:
#import "State.h"
@implementation State
@synthesize mystring;
+ (id)sharedInstance
{
static dispatch_once_t pred = 0;
__strong static id _sharedObject = nil;
dispatch_once(&pred, ^{
_sharedObject = [[self alloc] init]; // or some other init method
});
return _sharedObject;
}
@end
and then whenever you need it you could do:
import "State.h"
[State sharedInstance].mystring
Even simpler you can use singleton macro from here: https://gist.github.com/1057420#gistcomment-63896
I've personally found this pattern to be extremely useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.