Question

In my ViewController.m I have my void "Save Data":

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize myDatePicker, myTextField;

-(void)saveData
{
NSArray *value = [[NSArray alloc] initWithObjects:[myTextField text],[myDatePicker date], nil];
[value writeToFile:[self getFilePath] atomically:YES];

}

And I want to use my void "Save Data" in my AppDelegate.m :

- (void)applicationDidEnterBackground:(UIApplication *)application
{

[self.ViewController saveData];

}

But Xcode doesn't recognize the "ViewController" neither "saveData".

I don't know if I have to #import something in my AppDelegate, please help.

Was it helpful?

Solution

How you access your viewcontroller from the app delegate will depend on how many viewcontrollers you have / where it is in your current navigation hierarchy, etc etc. You could add a property for it, or perhaps it will be your app delegate's rootViewController.

However, you'd probably be better off listening out for a notification in your viewcontroller when the app enters the background. This means that the logic you need can be entirely self contained within your viewcontroller, and your app delegate doesn't need to know anything about it.

In your viewcontroller's initialization method, you can register to receive notifications:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(applicationDidEnterBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

Then, implement the method:

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [self saveData];
}

And make sure you also remove yourself as an observer in your viewcontroller's dealloc method:

-(void)dealloc 
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

OTHER TIPS

In your "appDelegate.m" implementation file at the top do this import ->

#import "ViewController.h"

This will make the custom class ViewController visible to the appDelegate.

In order to be able to call the -(void)saveData method from another class (in our case the other class is the AppDelegate class), this method needs to be declared in the public interface. That means ->

#import "ViewController.h"


@interface ViewController ()

-(void)saveData;

@end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top