使用未解析的标识符'对象'

时间:2016-03-10 04:53:03

标签: xcode swift

如何在代码中定义对象以及哪种类型?

 override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate=UIApplication.sharedApplication().delegate as! AppDelegate
    let context=appDelegate.managedObjectContext
    let request=NSFetchRequest(entityName:lineEntityName)
    do{
        let objects = try context.executeFetchRequest(request)
    }
    catch let error as NSError {

       print(error)
    }

    if let objectList=objects
    {
        for oneObject in objectList
        {
            let lineNum=oneObject.valueForKey(lineNumberKey) as integerValue
            let lineText=oneObject.valueForKey(lineTextKey) as String
            let lineField=lineFields(lineNum)
            textField.text=lineText
        }
    }
    else
    {
        print("There was an Error")
    }
    let app=UIApplication.sharedApplication()
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"applicationWillResignActiveNotification", name: UIApplicationWillResignActiveNotification, object: app)
    // Do any additional setup after loading the view, typically from a nib.
}

1 个答案:

答案 0 :(得分:0)

建议的方法是将所有好的代码放在do子句中,以解决问题。

executeFetchRequest返回一个非可选数组,因此可以省略可选绑定。

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDelegate.managedObjectContext
    let request = NSFetchRequest(entityName:lineEntityName)
    do {
        let objects = try context.executeFetchRequest(request)
        for oneObject in objects
        {
            let lineNum = oneObject.valueForKey(lineNumberKey) as integerValue
            let lineText = oneObject.valueForKey(lineTextKey) as String
            let lineField = lineFields(lineNum)
            textField.text = lineText
        }

        let app = UIApplication.sharedApplication()
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"applicationWillResignActiveNotification", name: UIApplicationWillResignActiveNotification, object: app)
        // Do any additional setup after loading the view, typically from a nib.
        }
    catch let error as NSError {
       print(error)
    }
}