我正在尝试存储Int
,然后在主屏幕视图控制器上阅读它。
这就是我正在做的事情
将值传递给最终视图控制器,我也想调用一个函数来存储数据
var gameScore = [NSManagedObject]()
func doSomething() {
if let myData = yourFinishScore {
// proving I passed score
print("Your score is \(myData)")
self.finishLabel.text = "\(myData)"
//call function to save data
saveName(myData)
} else {
// no data was obtained
print("No Data")
}
}
//
func saveName(score: Int) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let entity = NSEntityDescription.entityForName("Scores",
inManagedObjectContext:managedContext)
let yourScore = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
//3
yourScore.setValue(score, forKey: "famousGuy")
//print proves it's in thier correct
print("your score is\(yourScore)")
//4
do {
try managedContext.save()
//5
gameScore.append(yourScore)
print("worked, I saved")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
导航回第一个屏幕并尝试重新调用数据
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "Scores")
//3
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
famousGuysScore = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
if famousGuysScore.count > 0 {
print("There are objects")
self.myScore.text = "\(famousGuysScore[0])"
} else {
print("No objects")
}
我假设某条线上的某处我没有正确保存数据。我认为吸烟枪与gameScore.append(yourScore)
有关,我必须在这里做错事。
更新
非常肯定我只是对NSFetch
做了一些错误,假设我需要迭代我提取的内容以取出属性