【问题标题】:How to call a method on a class through the delegate (multitasking methods)?如何通过委托(多任务方法)调用类上的方法?
【发布时间】:2011-01-19 05:22:21
【问题描述】:

每次用户返回我的应用程序(多任务处理)时,我都需要在我的一个类上调用“刷新方法”。似乎对于多任务处理,我需要通过应用程序委托来执行此操作。那么在我的类自身上调用“刷新方法”的最佳方法是什么,而不是从应用程序委托中调用?

【问题讨论】:

    标签: iphone iphone-sdk-3.0 ios4


    【解决方案1】:

    正如 Vin 所说,您可以在 applicationWillEnterForeground 方法中添加它。 要更新您的 UI,您可以将应用程序委托设置为引用您的视图控制器并从那里调用更新方法。或者更好的是,您可以使用 NSNotificationCenter 来简单地通知您的其他类更新。

    如果您决定从应用程序委托中添加对视图控制器的引用,您只需创建一个属性。这是一种方法。但请注意,这仍取决于您的项目结构。

    SampleAppDelegate.h

    SampleViewController *viewController;
    ...
    @property (nonatomic, retain) SampleViewController *sampleViewController;
    ...
    

    SampleAppDelegate.m

    ...
    @synthesize sampleViewController;
    ... 
    // don't forget to release in dealloc
    [sampleViewController release]
    

    ...

    然后,您可以在加载视图控制器的任何位置分配应用程序委托的 sampleViewController 属性的值。因此,例如,如果您在应用程序委托的 didFinishLaunchingWithOptions 方法上以编程方式初始化您的视图控制器,只需将其分配到那里。

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
        // Override point for customization after application launch.
    
        SampleViewController *_sampleViewController = [[SampleViewController alloc] initWithFrame:CGRectMake(0,0,320,480)];
        self.sampleViewController = _sampleViewController;
    
        [window addSubview:_sampleViewController.view];
        [sampleViewController release];
    
        [self.window makeKeyAndVisible];
        return YES;
    } 
    

    如果您在应用程序委托之外加载视图控制器,则需要通过 sharedApplication 的委托属性访问应用程序委托。

    ((SampleAppDelegate*)[UIApplication sharedApplication] delegate).sampleViewController = _sampleViewController;
    

    然后您可以从 applicationWillEnterForeground 方法调用更新方法。

    - (void)applicationWillEnterForeground:(UIApplication *)application {
        /*
         Called as part of the transition from the background to the active state: here you can undo many of the changes made on entering the background.
         */ 
        [self.sampleViewController updateMyView];   
    }
    

    【讨论】:

    • 您好,我想此时,我的问题是如何创建对具有我的更新方法的视图控制器的引用?
    【解决方案2】:

    应用程序委托中的applicationWillEnterForeground 将在您的应用程序即将进入前台时被调用。在那里写下你的刷新逻辑。

    【讨论】:

    • 但我需要更新视图中的特定元素(即文本等)。我可以通过这种方法做到这一点吗?
    • 当您的应用程序在后台运行时,您可以将状态信息保存在 NSUserDefaults 中。然后,当应用程序重新启动时,检索状态信息并可以调用 setsNeedDisplay 以获取所需的视图以再次绘制它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2011-07-23
    相关资源
    最近更新 更多