无法弄清楚如何显示CoreData信息

时间:2015-08-18 02:55:29

标签: ios swift core-data

我开始了一个尝试熟悉CoreData的项目,但是我很难弄清楚如何在数据被保存后更新标签。

想法是:只有首次打开应用时,系统会弹出一个警告,要求输入用户名。然后将该用户名存储到CoreData,并且应用程序的主屏幕包含显示该用户名的标签。但由于某些原因,我无法更新标签的文字。

我在" updateName"中收到错误功能。在线" var person = people [0]"我得到以下内容:

  

"致命错误:数组索引超出范围。"

我不知道为什么0索引已经被设置为警报的文本字段。有什么想法吗?

class InitialViewController: UIViewController, UITextFieldDelegate {

var didRunBefore: Bool = NSUserDefaults.standardUserDefaults().boolForKey("didRunBefore")    

@IBOutlet weak var userGreeting: UILabel!

var people = [NSManagedObject]()
var alert = UIAlertController(title: "Hello!", message: "What's your name?", preferredStyle: .Alert)

override func viewDidAppear(animated: Bool) {

    if !didRunBefore {
        getUserName()
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "didRunBefore")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}


override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName:"Person")

    var error: NSError?

    let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as? [NSManagedObject]

    if let results = fetchedResults {
        people = results
    } else {
        println("Could not fetch \(error), \(error!.userInfo)")
    }
}


func getUserName() {

    userGreeting.text = ""      
    let saveAction = UIAlertAction(title: "Save", style: .Default) { (action: UIAlertAction!) -> Void in
        let textField = self.alert.textFields![0] as! UITextField
        self.saveName(textField.text)
    }


    let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction!) -> Void in
    }

    alert.addTextFieldWithConfigurationHandler {
        (textField: UITextField!) -> Void in
    }

    alert.addAction(saveAction)
    alert.addAction(cancelAction)

    func updateName() {
        var person = people[0]
        if let userName1 = person.valueForKey("name") as? String {
            userGreeting.text = "Hey there, \(userName1)!"
        }
    }

    presentViewController(alert, animated: true, completion: updateName)

}


 func saveName(name: String) {

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext!


    let entity1 =  NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
    let person = NSManagedObject(entity: entity1!, insertIntoManagedObjectContext: managedContext)


    person.setValue(name, forKey: "name")


    var error: NSError?
    if !managedContext.save(&error) {
        println("Could not save \(error), \(error?.userInfo)")
    }

    people[0] = person
   }
  }

0 个答案:

没有答案