SWIFT 之CoreData初试
SWIFT中使用CoreData来保存本地数据,在建立项目的时候把 "Use Core Data"选项选上
项目建立完成后点击后缀为 .xcdatamodeld的那个文件,点击右下角"Add Entity"添加一个Entity后可以修改其名称,接着在"Attributes"下面点击“+”号添加一个
Attribute
接着就可以上代码操作了,首先先添加引用
import CoreData
//It‘s necessary to code these two rows if you want to use CoreData
var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = applicationDelegate.managedObjectContext
//Get the entity by entityName
var entity = NSEntityDescription.entityForName("Notes", inManagedObjectContext: managedObjectContext!)
//Get the ManagedObject
var title = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext)
//Set the ManagedObject Value for key
title.setValue(text, forKey: "title")
var error: NSError?
//Save content
if(managedObjectContext?.save(&error) == nil){
}
//Get data from the CoreData
var applicationDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = applicationDelegate.managedObjectContext
var fetchRequest = NSFetchRequest(entityName: "Notes")
var error:NSError?
var fetchResults = managedObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if let results = fetchResults{
var notes = results
}else{
println(error)
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。