Swift version: 3.0
Xcode version: 8.0
iOS version: 10.0
since iOS10 and swift3.0, Apple's approach to CoreData has changed a lot, and the following is a great way to build an entity from 0 and implement its storage and reading capabilities.
Note: This is a convenience method, which is fast implementation. Therefore, you do not need to create a new class corresponding to entity
1. New Project
There's nothing to say, check use Core Data
2. Open the Xcdatamodeld file, create a new entity, we call it person, and then in the right side of the attributes add attributes, here added the name and age two properties, type optional
3. Get the context, which is encapsulated as a function for ease of use
Attention!! : Import CoreData is required within the corresponding Swift file
() -> NSManagedObjectContext { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext }
4. Store a new piece of data
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. Get the full contents of entity
//get all data for an entity Func Getperson () {let fetchrequest = nsfetc Hrequest<nsfetchrequestresult> (entityname: "person ") do {let searchresults = try g Etcontext (). Fetch (fetchrequest) print ( "numbers of \ ( Searchresults.count) for p in (searchresults as! [Nsmanagedobject]) {print ( "name: \ (P.value (forkey:" Name ")!)}} catch {print (Error)}}
So that the data can be completely written into the app itself.
Put a link to the full demo
Full Demo
Effect
Reference:
https://learnappdevelopment.com/uncategorized/how-to-use-core-data-in-ios-10-swift-3/
Swift 3.0 uses core Data