[英]How to call a method on a class through the delegate (multitasking methods)?
每當用戶返回我的應用程序(多任務處理)時,我需要在我的一個類中調用“刷新方法”。 似乎對於多任務,我需要通過應用程序委托來執行此操作。 那么,從我的類本身上調用“刷新方法”的最佳方法是什么呢?
正如Vin所提到的,您可以將其添加到applicationWillEnterForeground方法中。 要更新UI,可以將應用程序委托設置為對視圖控制器具有引用,然后從那里調用update方法。 或者更好的是,您可以使用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方法調用update方法。
- (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];
}
applicationWillEnterForeground
在應用程序委托時,你的應用程序僅僅是即將來到的前景將被調用。 在此處編寫刷新邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.