我正在尝试使用会话检查现有登录但是我被抛出此错误
“AnyObject?不能转换为'NSString';你的意思是用'as!'迫使低垂?
在这行代码
self.usernameLabel.text = prefs.valueForKey("USERNAME") as NSString
完整的代码块是
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var usernameLabel: UILabel!
//Check for existing login, else show login
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let prefs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1) {
self.performSegueWithIdentifier("goToLogin", sender: self)
} else {
self.usernameLabel.text = prefs.valueForKey("USERNAME") as NSString
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
解决问题的最佳方法是什么?
答案 0 :(得分:3)
试试这个......
if let username = prefs.valueForKey("USERNAME") as? String{
self.usernameLabel.text = username
}
或者如果你想使用NSString ..(只是一个选项)
if let username = prefs.valueForKey("USERNAME") as? NSString{
self.usernameLabel.text = username
}
答案 1 :(得分:0)
将NSString更改为String,
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
它的工作正常,希望它有用