anyobject 在 SWIFT 中没有成员命名的 objectforkey

anyobject does not have a membered named objectforkey in SWIFT

我正在尝试从通知中获取 objectForKey,但出现错误:anyobject does not have a membered named objectforkey

我使用的代码是:

func executeAlbum(notification:NSNotification){
        let data = notification.userInfo.objectForKey("data") as [AlbumModel] // ERROR HERE
        self.sources = data
        self.albumTable?.reloadData()
    }

谁能告诉我为什么它不起作用以及等效的是什么?

谢谢

您的 notification.userInfoAnyObject 类型。因此您不能使用 objectForKey("") 因为 AnyObject 不提供此方法。您可能需要投射 notification.userInfo 但我不知道那背后是什么。

objectForKey 方法是 NSDictionary 的一种方法,在您的情况下 notification.userInfo return [NSObject : AnyObject]? 类型是字典。要从 "swift dictionary" 获取对象,您需要使用其下标方法,因此:

func executeAlbum(notification:NSNotification){
        let data:[AlbumModel]? = notification.userInfo?["data"] as? [AlbumModel] // ERROR HERE -> Not anymore
        self.sources = data
        self.albumTable?.reloadData()
    }

应该做的工作