Reputation: 25
In my application has a view controller named "Home
" with a textField
.
I read about applicationDidEnterBackground
and applicationWillTerminate
methods in the AppDelegate
file.
I know how to create, save, read data from a file.
My question is, How I can get an NSString
from the "Home
" viewController (that there store the textField
data) to the AppDelegate applicationDidEnterBackground
method and do there all my things with that data?
Upvotes: 0
Views: 127
Reputation: 531
You can do this with the help of this inside your controller:
-(id)init
{
if((self = [super init]))
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:[UIApplication sharedApplication]];
}
return self;
}
-(void)appDidEnterBackground:(NSNotification *)note {
NSLog(@"appDidEnterBackground");
}
you can also use applicationWillTerminate in place of UIApplicationDidEnterBackgroundNotification
Upvotes: 0
Reputation: 347
You could use NSNotificationCenter to register for a notification in your view controller that fires off whenever you enter applicationDidEnterBackground or applicationWillTerminate.
So in either of those methods you put something like
[[NSNotificationCenter defaultCenter] postNotificationName:@"someDescriptiveName" object:self userInfo:@{@"key" : @"value"}];
userInfo expects an NSDicitonary and you can pass it any type of object in there, in your case you dont need to pass anything from here back to your viewcontroller, your just using it as a means to let your view controller know the app is closing.
In your view controller you would register for that notification with something like this
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodToCall:) name:@"someDescriptiveName" object:nil];
Then whenever your appDelegate post that notification, your view controller which is registered to listen for it would fire off "methodToCall" which can be a method you right to do anything and it takes in an nsnotification which then lets you access the nsdicitonary its carrying.
- (void)methodToCall:(NSNotification *)notif{
NSLog(@"methodToCall fired with data %@",[[notif userInfo]valueForKey:@"key"]);}
Upvotes: 1