在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
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) }
|
请发表评论