您的位置:首页 > 移动开发 > Swift

coredata swift 简单入门

2015-09-25 17:03 204 查看

建立项目与插入数据

使用coredata来保存数据,coredata是一个很好的数据存储框架。 在新建的项目中只要勾选core data即可


然后我们在项目的左侧文件目录里面就发现了一个文件和往常的不一样,多了一个模块化的文件,

就是上图中coredatatest.xcdatamodeld数据的模型文件,然后打开AppDelegate.swift,发现多了几个
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "LivinSpring.coredatatest" in the application's documents Application Support directory.let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()

lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.let modelURL = NSBundle.mainBundle().URLForResource("coredatatest", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.// Create the coordinator and storevar coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("coredatatest.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}

return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

// MARK: - Core Data Saving supportfunc saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}

然后我们现在来编辑数据模型,打开左侧的xcdatamodeld文件

暂时是空的,左下角的Add Entity 按钮点击后,就可以添加实例,并且编辑属性和数据类型,完成这步的时候,已经可以使用这个数据模型来进行数据存储和读取,但是,有的时候你想要使用这个模型的类来在代码中一些数据传递,构造什么的,那么也可以构造一个类,自己写一个也可以继承NSManagedObject,或者可以通过xcode的快速构造生产一个类。 我简单的构造了一个entity,然后创建了一个属性name

在editor工具中创建一个子类

就这样恨简单就创建好了,
import Foundation
import CoreData

class TestEntity: NSManagedObject {

@NSManaged var name: String

}

这样就完成了,这些当然也可以手写,只是xcode给了一个更加便利的方法。
然后我们开始进行存储操作 比如我建了一个叫做TestEntity,里面有两个 属性一个叫name,一个时phonenum,(这里其实是我更新了xcode6.1之后重新建立的项目,因为不知道什么原因原来在6下面建的项目在6.1中报错了,位置还是在自动生成的AppDelegate中,所以我重新建立了新项目)
//1var appDel = UIApplication.sharedApplication().delegate as AppDelegate //获取appdelvar context = appDel.managedObjectContext //获取存储的上下文//2var entity=NSEntityDescription.entityForName("TestEntity", inManagedObjectContext: context!)
var person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: context)// 这里如果做了转型的话其实也可以直接类似类的属性进行赋值一样

person.setValue("bob", forKey: "name")
person.setValue(123, forKey: "phonenum")
var error:NSError?

if (context?.save(&error) == nil){
println("could not save \(error)")
}else{
println("save is ok  \(context)")
}

var fectchRequest = NSFetchRequest(entityName: "TestEntity")
var fectchRuslt = context?.executeFetchRequest(fectchRequest, error: &error)
println( fectchRuslt?.count)//查询有多少个记录

但是问题来了,运行报错
2014-10-30 20:47:50.683 coredatatest2[589:14431] CoreData: warning: Unable to load class named 'TestEntity' for entity 'TestEntity'.  Class not found, using default NSManagedObject instead.

各种谷歌百度之后,发现一个问题https://developer.apple.com/library/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html 参考上面这个连接,然后发现需要设置

把项目名称增加到这个class的名称前面,就ok了。
另外上面所说的插入数据的时候有个类型转换的话可以是这样的
var newperson:TestEntity = NSEntityDescription.insertNewObjectForEntityForName("TestEntity", inManagedObjectContext: context!) as TestEntity
var error:NSError?
newperson.name="helo"
newperson.phonenum=234

这样看着挺容易理解的。最后使用context对象的save保存就可以了,如果需要错误数据也可以使用一个error

查询数据

查询数据最重要的两个一个是 NSSortDescriptor 一个是 NSPredicate 前者是一个排序的设置,后者是一个被称为查询谓语的东东,其实相当于sql语句。
 var fectchRequest = NSFetchRequest(entityName: "TestEntity")
var sortDescrpitor = NSSortDescriptor(key: "name", ascending: true,selector: Selector("localizedStandardCompare:")) //根据name排序,后面有个selectot参数,直接使用内置的方法进行查询,这里的这个和oc写法差别很大:selector:@selector(localizedStandardCompare:)

var zoename = "zoe"var predicate:NSPredicate = NSPredicate(format: "name contains '\(zoename)'")!//   或者(format:"name contains %@",zoename ),或者是(format:"name contains 'zoe'") ; 除了contains以外还有很多其他的一些谓语关键词,也可以重叠谓语用and这样的连接词
fectchRequest.sortDescriptors = [sortDescrpitor]
fectchRequest.predicate = predicate

var fectchRuslt = context?.executeFetchRequest(fectchRequest, error: &error) as [NSManagedObject]?

更多谓语关键词参考apple的开发文档
更多的selector的compare参考apple的文档

删除数据

删除很好理解的,就是直接我们request一些内容,然后让context来删除。
    var fetchRsult:[SectionEntity] =     context?.executeFetchRequest(sectionFetchRequst, error: &error) as [SectionEntity]//这里的fetchrsult就是我们通过request获得的结果,然后遍历这些结果,让context来删除它们。if (error != nil) {
println("dele error:\(error)")
}else{
for one:NSManagedObject in fetchRsult {
println(one.description)
context?.deleteObject(one)
}
}
if (context?.hasChanges != nil){
context?.save(&error)
}else{
println("context save error:\(error)")

}

Swift 2.0

Swift2.0 已经发布,CoreData上面也修改很大,主要是try catch在Context save的时候把握错误信息。

来源: <http://www.zoejblog.com/ioscoredata-swift-jian-dan-ru-men/>

来自为知笔记(Wiz)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: