swift3.0 coredata 的使用

Posted brave-sailor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift3.0 coredata 的使用相关的知识,希望对你有一定的参考价值。

//swift3.0在语法上有很大的改变,以简单的增删改查为例,如下:

//User类如下:

import Foundation

import CoreData

extension User {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<User> {

        return NSFetchRequest<User>(entityName: "User");

    }

    @NSManaged public var address: String?

    @NSManaged public var email: String?

    @NSManaged public var headImg: NSData?

    @NSManaged public var isLeave: Bool

    @NSManaged public var name: String?

    @NSManaged public var tel: String?

    @NSManaged public var birthDay: String?

}

 

//CoreDataTools 类如下:该类用于操作coredata

 

import UIKit


class CoreDataTools: NSObject {

}

///CoreData操作

let EntityName = "User"

 

//

func addCoreData()

{   

 

    let entity = NSEntityDescription.insertNewObject(forEntityName: EntityName, into: appDelegate.managedObjectContext) as! User

    entity.name"周杰伦"

    entity.tel ="123456789952"

    do

    {

        try appDelegate.managedObjectContext.save()

        print("添加成功 ~ ~ ")

    }catch

    {

        print("添加失败!!")

    }

}




//

func deleteCoreData(ConditionDic conditionDic:NSMutableDictionary)

{

    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: EntityName)

    let condition = "name=‘周杰伦‘"

    let predicate = NSPredicate(format: condition, "")

    request.predicate = predicate

    do{

        //查询满足条件的联系人

        let resultsList = try appDelegate.managedObjectContext.fetch(request) as! [User] as NSArray

        if resultsList.count != 0 {//若结果为多条,则只删除第一条,可根据你的需要做改动

            appDelegate.managedObjectContext.delete(resultsList[0] as! NSManagedObject)

            try appDelegate.managedObjectContext.save()

            print("delete success ~ ~")

        }else{

            print("删除失败! 没有符合条件的联系人!")

        }

    }catch{

        print("delete fail !")

    }

}


//

func updateDataWithCoreData(Model userModel:UserModel, Where condiArray:NSArray)

{

    let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: EntityName)

    let entity:NSEntityDescription = NSEntityDescription.entity(forEntityName: EntityName, in: appDelegate.managedObjectContext)!

 

    let condition = "name=‘周杰伦‘"

    let predicate = NSPredicate(format: condition,"")

    request.entity = entity

    request.predicate = predicate

    do{

        let userList = try appDelegate.managedObjectContext.fetch(request) as! [User] as NSArray

        if userList.count != 0 {

            let user = userList[0] as! User            

            user.name = "小公举"           

            try appDelegate.managedObjectContext.save()

            print("修改成功 ~ ~")

        }else{

            print("修改失败,没有符合条件的联系人!")

        }

    }catch{

        print("修改失败 ~ ~")

    }

    

}

//

func selectDataFromCoreData() -> NSArray

{

    var dataSource = NSArray()

    let request : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest()

    let entity:NSEntityDescription? = NSEntityDescription.entity(forEntityName: EntityName, in: appDelegate.managedObjectContext)

    request.entity = entity

    do{

        dataSource = try appDelegate.managedObjectContext.fetch(request) as! [User] as NSArray

        print("数据读取成功 ~ ~")

    }catch{

        print("get_coredata_fail!")

    }

    

    return dataSource

}


 

//查询所有数据并输出

func printAllDataWithCoreData()

{

    let array = getDataFromCoreData()

    for item in array {

        let user = item as! User

        print("name=",user.name,"tel=",user.tel,"email=",user.email,"address=",user.address)

    }

}


//注:appDelegate.managedObjectContext 为定义的全局变量,在Appdelegateclass范围外定义如下:

//let application = UIApplication.shared

//let appDelegate = application.delegate as! AppDelegate

 
 

以上是关于swift3.0 coredata 的使用的主要内容,如果未能解决你的问题,请参考以下文章

使用 Swift 3.0 将 CoreData 保存到 Web 服务器

浅谈SwiftUI 3.0新加入的CoreData动态FetchRequest过滤与排序特性

以一个名称将多个对象保存到 coredata

如何以一个名称将多个对象保存到 CoreData

Swift 3“任何”类型的值没有成员“valueForKey”

Swift 3.0 - 核心数据 / 意外发现 nil