2011-12-26 98 views
0

我剛剛注意到我的iPhone/iPad應用程序中存在一個相當嚴重的錯誤:我有一個名爲AppDelegate的類,它實現UIApplicationDelegate協議 - 就像每個iPhone應用程序一樣。我正在使用核心數據,並且AppDelegate設置了我的託管對象上下文(我大多隻保留了Xcode模板的默認方法)。AppDelegate的兩個實例,如何解決?

現在我需要在我的應用程序的一些地方管理對象上下文,我還想從幾個地方調用-saveContext方法。所以我用了單件模式,並添加一個類的方法+ (AppDelegate *)sharedAppDelegate是這樣實現的:

+ (AppDelegate *)sharedAppDelegate 
{ 
    static dispatch_once_t pred = 0; 
    __strong static id _sharedObject = nil; 
    dispatch_once(&pred,^{ 
     _sharedObject = [[self alloc] init]; 
    }); 
    return _sharedObject; 
} 

一切正常爲止。然而,現在我試圖訪問sharedAppDelegateUIWindow屬性,並注意到它是nil。起初我很困惑,但後來我意識到,我的第一個方法main創建的AppDelegate一個實例,它創建於-application:didFinishLaunchingWithOptions:UIWindow和視圖控制器,然後,-sharedAppDelegate創建另一個!我覺得很奇怪,我的應用程序似乎目前工作得很好,因爲例如只有第一個實例在應用程序存在時調用-saveContext

無論如何,我想改變它,以便main方法也使用sharedAppDelegate。這是否意味着我需要重寫-init方法?我怎樣才能防止無限循環(-sharedAppDelegate畢竟也調用init)?我應該使全球範圍的變量_sharedObject

+0

爲什麼選擇倒票? – fabian789 2011-12-26 10:56:24

回答

5

您不創建您自己的應用程序委託實例。 UIKit框架在應用程序啓動時爲您創建一個。您可以從UIApplication的delegate方法中獲取當前的應用程序代理。所以,當你想獲得你的共享管理對象上下文:

// Get the instance of your delegate created by the framework when the app starts 
AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate]; 

// Assuming you're using the default methods from the template... 
NSManagedObjectContext* context = [appDelegate managedObjectContext]; 

你總是可以得到當前單身的UIApplication反對與sharedApplication方法,您可以使用delegate方法上總是讓你的應用程序代理的正確實例應用實例。

+0

我只是在打字! +1 – 2011-12-26 10:10:55

+0

哦,我沒有意識到這一點。謝謝! – fabian789 2011-12-26 10:18:36