سؤال

I want to access a NSString from AppDelegate.m that is located inside ViewController.m.

I have a Single View Application, and i want to save my NSString using applicationDidEnterBackground: inside AppDelegate.m.

The NSString is located inside ViewController.m, and is not declared in AppDelegate.m.

I tried to declare it in AppDelegate.h and then access it in the ViewController.m (And reversed).

ViewController.h:

@interface MyAppViewController : UIViewController {
    NSString *MyString;
}

AppDelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *)application {
   NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
   [defaults setObject:MyString forKey:@"SavedString"];
   [defaults synchronize];
}
هل كانت مفيدة؟

المحلول

You can register MyAppViewController to observer UIApplicationDidEnterBackgroundNotification like this:

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

and in the method goToBackground you can save in NSUserDefaults the MyString.

نصائح أخرى

Instance variables in one class are not available to methods of a different class. You can expose an interface to get and set instance variables from outside a class by either defining getter and setter methods, or by defining properties (which are essentially syntactic sugar for getter and setter methods. See the Declared Properties chapter of The Objective-C Programming Language for details.

Well, if MyString belongs to the MyAppViewController object, you at the very least need a reference to the controller. Assume you call it controller.

Then, if you want MyString to be accessible as a property to other classes, you have to declare it as such:

@interface MyAppViewController : UIViewController
@property (strong, nonatomic) NSString *MyString;
@end

Then in your app delegate:

- (void)applicationWillTerminate:(UIApplication *)application {
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:controller.MyString forKey:@"MyString"]; //<-- This is where it all goes wrong. MyString is shown as undeclared identifier.
    [defaults synchronize];
}

Also as a side note, you might want to double check your naming conventions for clarity.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top