2012-04-24 1 views
0

ViewController.m 안에있는 AppDelegate.m에서 NSString에 액세스하고 싶습니다. Xcode iPhone SDK (5.x) - AppDelegate 내의 NSString에 액세스하기

내가

단일보기 응용 프로그램이 있고, 나는 AppDelegate.m 내부 applicationDidEnterBackground:를 사용하여 내 NSString을 저장할.

NSStringViewController.m 안에 있으며 AppDelegate.m에 선언되어 있지 않습니다.

AppDelegate.h에 신고하려고 시도한 다음 ViewController.m (역방향)으로 액세스하려고했습니다.

ViewController.h

:

@interface MyAppViewController : UIViewController { 
    NSString *MyString; 
} 

AppDelegate.m : 한 클래스

- (void)applicationDidEnterBackground:(UIApplication *)application { 
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; 
    [defaults setObject:MyString forKey:@"SavedString"]; 
    [defaults synchronize]; 
} 

답변

1

이 같은 관찰자 UIApplicationDidEnterBackgroundNotification에 MyAppViewController 등록 할 수 있습니다.

0

인스턴스 변수가 다른 클래스의 방법을 사용할 수 없다. getter 및 setter 메서드를 정의하거나 속성 (getter 및 setter 메서드의 본질적인 구문 설탕)을 정의하여 클래스 외부에서 인스턴스 변수를 가져오고 설정하는 인터페이스를 표시 할 수 있습니다. Objective-C 프로그래밍 언어의 Declared Properties 장을 참조하십시오. 자세한 내용은.

0

음, MyString의이 MyAppViewController 객체에 속하는 경우, 당신은 적어도 컨트롤러에 대한 참조를해야합니다. 당신이 controller를 호출 가정합니다.

을 그런 다음 MyString의이 같은 액세스하려면, 속성을 다른 클래스에 추가하려면 다음과 같이 선언해야합니다.

@interface MyAppViewController : UIViewController 
@property (strong, nonatomic) NSString *MyString; 
@end 
0 앱 위임에서 다음

:

- (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]; 
} 

는 또한 보조 노트로, 당신은 명확성을 위해 당신의 이름 지정 규칙을 다시 한 번 확인 할 수 있습니다.

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

을하고 NSUserDefaults MyString에 저장할 수 있습니다 goToBackground 방법에있어서 :