Swift 3.0 使用Core Data

news/2024/7/20 22:30:04 标签: ios, swift, xcode, 苹果

swift版本:3.0
Xcode版本:8.0
iOS版本:10.0

自iOS10 和swift3.0 之后,苹果的访问CoreData的方法发生了很大改变,简洁了许多,下面的内容是从0开始建立一个entity,并实现其存储和读取的功能。
注:这个是一种convenience方法,即快速实现。所以并不需要新建对应于entity的class
1.新建工程
没什么好说的,勾选 Use Core Data

2.打开xcdatamodeld文件,新建一个entity,我们叫它Person,然后在右侧的Attributes里面增加属性,这里添加了name和age两个属性,type自选
这里写图片描述

3.获取Context,为了方便使用,这里封装成一个函数
注意!!:在对应的swift文件内需要先 import CoreData

    func getContext () -> NSManagedObjectContext {
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }

4.存储一条新数据

func storePerson(name:String, age:Int){
       let context = getContext()
       // 定义一个entity,这个entity一定要在xcdatamodeld中做好定义
       let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)

       let person = NSManagedObject(entity: entity!, insertInto: context)

       person.setValue(name, forKey: "name")
       person.setValue(age, forKey: "age")

       do {
       try context.save()
           print("saved")
       }catch{
           print(error)
       }
}

5.获取entity的全部内容

// 获取某一entity的所有数据
func getPerson(){
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
        do {
            let searchResults = try getContext().fetch(fetchRequest)
            print("numbers of \(searchResults.count)")

            for p in (searchResults as! [NSManagedObject]){
                print("name:  \(p.value(forKey: "name")!) age: \(p.value(forKey: "age")!)")
            }
        } catch  {
            print(error)
        }
    }

这样数据就可以完全的写入APP内部了

放上完整demo的链接
完整demo下载

效果截图
这里写图片描述
这里写图片描述

参考:

https://learnappdevelopment.com/uncategorized/how-to-use-core-data-in-ios-10-swift-3/


http://www.niftyadmin.cn/n/1228954.html

相关文章

iOS开发bug消灭之:Your application has presented a UIAlertController of style ...

Your application has presented a UIAlertController of style UIAlertControllerStyleActionSheet. swift版本&#xff1a;3.0 Xcode版本&#xff1a;8.0 错误全文&#xff1a; Your application has presented a UIAlertController of style UIAlertControllerStyleActi…

iOS开发bug消灭之:Invalid update: invalid number of rows in section 0.

Invalid update: invalid number of rows in section 0. swift版本&#xff1a;3.0 Xcode版本&#xff1a;8.0 错误全文&#xff1a; Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (8) mu…

iOS开发bug消灭之:Implicit use of 'self' in closure; use 'self.' to make capture semantics explicit

错误全文&#xff1a; Implicit use of ‘self’ in closure; use ‘self.’ to make capture semantics explicit swift版本&#xff1a;3.0 Xcode版本&#xff1a;8.0 错误原因&#xff1a; 在closure&#xff08;闭包&#xff09;内调用当前对象的属性或方法的时候&…

iOS开发bug消灭之:Could not cast value of type 'UINavigationController' to 'RedShirt.AddEmployeeTableVi...

swift版本&#xff1a;3.0 Xcode版本&#xff1a;8.0 错误全文&#xff1a; Could not cast value of type ‘UINavigationController’ to ‘RedShirt.AddEmployeeTableViewController’ 错误原因&#xff1a; 从AController segue 到BController的时候&#xff0c;由于B…

restore和recover的区别

restore 是还原物理文件 recover 是用日志恢复到一致 用了RMAN备份后就必须要用restore还原&#xff0c;然后才用recover恢复 restore——还原&#xff0c;与backup相对&#xff0c;从备份读出恢复备份的数据。 recover——恢复&#xff0c;把restore回来的数据经过一番处理变成…

iOS开发中有关Segue传输的流程研究

swift版本&#xff1a;3.0 Xcode版本&#xff1a;8.0 segue是ios开发中用来在不同的controller之间跳转和传输数据的核心方法&#xff0c;里面的一些常用的函数有prepare, shouldPerformSegue, performSegue等&#xff0c;但是他们之间的使用方法和调用顺序经常搞不清楚。针对…

C++11 中的高阶函数

看到了Swift里面有高阶函数map,filter,reduce。发现非常好用&#xff0c;以前写类似的东西要写好多循环。没怎么接触过函数式编程&#xff0c;在网上找了一下C的对应方法&#xff0c;分别为std::transform,std::remove_if,std::accumulate&#xff0c;总结如下&#xff1a; 首…

C++ 如何 int 转 string

写c的时候经常需要做int到string的转换。 下面是最简洁的方法 #include <string> std::string str std::to_string(35); to_string()函数不只能转换int&#xff0c;还可以转换各种float, double数据 c 中的定义如下&#xff1a; _LIBCPP_FUNC_VIS string to_strin…