AppDelegate:从ViewController获取价值?

时间:2010-02-15 16:37:54

标签: iphone objective-c uiviewcontroller

我想参加

- (void)applicationWillTerminate:(UIApplication *)application

来自视图控制器类的变量。 我已经构建了一个tabbar应用程序,并且只将tabbar控制器添加到了appdelegate。

[window addSubview:tabBarController.view];

如何从TestViewController获取变量:

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface TestViewController : UIViewController {
    IBOutlet UILabel *testLabel;
    NSString *currentString; //Value that i want to save at applicationWillTerminate
}

@property (nonatomic, retain) UILabel* testLabel;
@property (nonatomic, retain) NSString* currentString;

@end

3 个答案:

答案 0 :(得分:2)

当你到达applicationWillTerminate时,TestViewController还没有被释放,这有点偶然 - 在你的应用程序中将该值存储得更高可能是有意义的。这种方法是始终将currentString存储在UIApplicationDelegate中,以便您以后不必获取它:

@implementation TestViewController
- (void)setCurrentString:(NSString *)currentString {
    ((MyAppDelegate *)[[UIApplication sharedApplication] delegate]).currentString = currentString;
} 
@end

答案 1 :(得分:1)

扩展dbarker的答案,听起来你真正需要的是在数据模型中保存currentString值。适当的地方是在viewController本身。

如果您的数据模型只是一个字符串,则可以在app delegate中创建一个属性来保存它。然后只要视图关闭时视图中的currentString值和/或其值发生变化,viewController就会写入app delegate属性。

这样,无论您打开多少个视图,数据(无论如何都是应用程序的整个点)总是在应用程序关闭时就位。

控制器将信息从接口移动到数据模型是正确的角色。严格地说,viewController不应该存储除接口本身所需的任何数据。这应该是viewControllers通过使用从接口获取的值向数据模型对象发送消息而设置的数据模型的属性。

在这种情况下,视图控制器中不会有currentString属性。相反,他们将拥有一个只是对数据模型的currentString属性的引用的属性。视图控制器将不断更新该属性,但不会自行存储任何内容。

这种设计的优点是显而易见的。如果您需要在应用中的任何位置使用该值,则可以使用一个位置和一个调用来获取它。除了数据模型之外,应用程序的任何部分都不需要知道应用程序的任何其他部分的存在。

答案 2 :(得分:0)

不是100%肯定你的要求,但这是一个猜测:
UITabBarController有一个名为viewControllers的属性,它返回与tabbar关联的所有视图控制器。

假设TestViewController是您可以通过以下方式获得的第一个选项卡:

- (void)applicationWillTerminate:(UIApplication *)application {
    TestViewController* test_view_controller = [tabBarController.viewControllers objectAtIndex:0] ;
    NSString* value = test_view_controller.currentString ;
}

请注意,如果您决定稍后将TestViewController移动到标签栏中的其他位置,这将会中断。

- 编辑 - 检查所有控制器并从控制器中获取TestViewController类型的字符串。

NSString* value = nil ;
for ( id unknownController in tabBarController.viewControllers ) {
  if ( [unknownController isKindOfClass:[TestViewController class]] ) {
     value = ((TestViewController*)unknownController).currentString ; 
  }
}
// value should be the value of the string.
相关问题