Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

ios - [NSObject : AnyObject]?' does not have a member named 'subscript' error in Xcode 6 beta 6

I used the below couple of code lines to get the frame of the keyboard when its shown on the screen. I've registered to UIKeyboardDidShowNotification notification.

func keyboardWasShown(notification: NSNotification) {
    var info = notification.userInfo
    var keyboardFrame: CGRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue()
}

This used to work in beta 5. I downloaded the latest Xcode 6 version which is beta 6 and this error occurred at the second line.

'[NSObject : AnyObject]?' does not have a member named 'objectForKey'

After some Googling, I came across this solution. And I changed it like so,

var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()

But it seems that's also outdated now. Because I get this error now.

'[NSObject : AnyObject]?' does not have a member named 'subscript'

I can't figure out this error or how to resolve it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in the Xcode 6 beta 6 release notes, a large number of Foundation APIs have been audited for optional conformance. These changes replace T! with either T? or T depending on whether the value can be null (or not) respectively.

notification.userInfo is now an optional dictionary:

class NSNotification : NSObject, NSCopying, NSCoding {
    // ...
    var userInfo: [NSObject : AnyObject]? { get }
    // ...
}

so you have to unwrap it. If you know that userInfo is not nil then you can simply use a "forced unwrapping":

var info = notification.userInfo!

but note that this will crash at runtime if userInfo is nil.

Otherwise better use an optional assignment:

if let info = notification.userInfo {
    var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
} else {
    // no userInfo dictionary present
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...