2015-11-16 25 views
0

後,我有一個名爲CoreSpotlight(NSObject類)類,這個類我需要對通知做出反應的方法。我試圖在應用程序委託中創建此類的一個實例,並且我調用該方法將實例本身添加爲觀察者。方法沒有得到所謂的添加類作爲觀察員通知

func addCoreSpotLightAsObserverForItemInstallerNotifications() { 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "addNewInstalledItemToSpotlightIndex:", name: "ItemInstallerItemInstalledNotification", object: nil) 
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "removeUninstalledItemFromSpotlightIndex:", name: "ItemInstallerItemUninstalledNotification", object: nil) 
    NSLog("Corespotlight added as observer///////////////////////////////////////////") 
} 

這是我如何調用應用程序didFinishLaunchingWithOptions

let coreSpotlightInstanceClass = CoreSpotlight() 
    coreSpotlightInstanceClass.addCoreSpotLightAsObserverForItemInstallerNotifications() 

出於某種原因,該方法不響應通知在應用程序委託的方法。預先感謝您

回答

1

您正在創建CoreSpotlight的實例作爲didFinishLaunchingWithOptions函數中的局部變量,因此只要此函數退出,對象將被釋放。

您應該創建一個實例屬性來存儲引用;

class AppDelegate: UIResponder, UIApplicationDelegate { 

    var window: UIWindow? 

    let spotlightHandler = CoreSpotlight() 

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
     // Override point for customization after application launch. 

     self.spotlightHandler.addCoreSpotLightAsObserverForItemInstallerNotifications() 
     return true 
    } 

雖然你的代碼將是清潔的,如果你只是調用addCoreSpotLightAsObserverForItemInstallerNotifications(我不得不說這是一個非常可怕的函數名太)在CoreSpotlight init功能。那麼除了在保留變量中實例化該類的實例之外,您不需要做任何其他操作。

+0

笑啊,我需要在名稱工作。什麼喲意味着如果你把addCoreSpotLightAsObserverForItemInstallerNotifications'的'內容轉化爲'CoreSpotlight'那麼觀察者會在該行註冊的'的init()'方法 –

+0

「雖然你的代碼會,如果你只是調用addCoreSpotLightAsObserverForItemInstallerNotifications更清潔」讓' spotlightHandler = CoreSpotlight()',你不需要'didFinishLaunchingWithOptions'中的任何代碼 – Paulw11

+0

@ Paultw11會做!謝謝你! –

相關問題