【发布时间】:2016-09-15 12:00:59
【问题描述】:
我是 CoreData 的新手。我构建了一个非常简单的计数器界面,每次点击视图时都会将数字增加 1。非常简单。需要实现 CoreData 以便数字在下次打开时仍然存在。
这是我的代码
类级属性
var timer = Int()
var name = Int()
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
let context: NSManagedObjectContext = appDel.managedObjectContext
do {
let request = NSFetchRequest(entityName: "Model")
let results = try context.executeFetchRequest(request)
for item in results{
let name = item.valueForKey("counter") as! Int
print("The counter # saved in Core Data is: \(name)")
counterOutlet.text = "\(name)"
// Updated
if name > timer {
timer = name
}
}
}
catch {
print("Error retrieving from Core Data.")
}
}
查看已点击(增加计数器,并保存到 CD
@IBAction func tapGestureRecognizerTapped(sender: UITapGestureRecognizer) {
timer += 1
print(timer)
counterOutlet.text = "\(timer)"
let context: NSManagedObjectContext = appDel.managedObjectContext
// Add stuff to CD
let mySavedCounter = NSEntityDescription.insertNewObjectForEntityForName("Model", inManagedObjectContext: context)
mySavedCounter.setValue(timer, forKey: "counter")
// Add the info to the entity!
do {
try context.save()
}
catch {
print("Error saving to Core Data.")
}
}
当我第一次加载应用程序时,计数器为 0(应该是)。我可以点击视图以将计数器增加 1。工作正常。
当我硬关闭应用程序时,我重新打开它以查看我离开的值仍然存在! (太棒了!!)控制台日志显示如下:(我在 15 岁时关闭了应用程序。)
The counter # saved in Core Data is: 1
The counter # saved in Core Data is: 2
The counter # saved in Core Data is: 3
The counter # saved in Core Data is: 4
The counter # saved in Core Data is: 5
The counter # saved in Core Data is: 6
The counter # saved in Core Data is: 7
The counter # saved in Core Data is: 8
The counter # saved in Core Data is: 9
The counter # saved in Core Data is: 10
The counter # saved in Core Data is: 11
The counter # saved in Core Data is: 12
The counter # saved in Core Data is: 13
The counter # saved in Core Data is: 14
The counter # saved in Core Data is: 15
现在我需要调试的问题:
点击视图后,计数器将重置为 0,然后从那里递增。不应该从 15 递增!
我怎样才能修复这个错误以使计数器递增到保存的数字(在本例中为 15)。此外,我创建了一个 NSManagedObject 子类,但似乎没有使用它。上面的代码是使用几个 youtube 教程创建的。可以通过使用子类来优化此代码吗?每次点击视图时将此计数器保存到 CD 是否是不好的做法?
【问题讨论】:
-
如果你想要坚持的唯一东西就是计数器,你为什么不直接使用 NSUserDefaults 而不是将 CoreData 堆栈引入应用程序?
-
@Eugenezhenya Gordin - 简短的回答是我只想练习 coredata。谢谢你的建议!