美文网首页iOS
002 Core Data系列

002 Core Data系列

作者: MWY | 来源:发表于2015-11-25 21:12 被阅读62次

    简单的demo演示Core Data是如何工作的

    Core Data存储数据
    func saveName(name: String) {
            
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            
            let managedContext = appDelegate.managedObjectContext
            let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)
            
            
            let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
            person.setValue(name, forKey: "name")
            
            do {
                try managedContext.save()
            }catch {
                print("Error")
            }
            
            people.append(person)
            
        }
    
    
    Core Data读取数据
    
        override func viewWillAppear(animated: Bool) {
            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDelegate.managedObjectContext
            
            let fetchRequest = NSFetchRequest(entityName: "Person")
            
            var fetchRequests = [NSManagedObject]()
            
            do {
                fetchRequests = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
            }catch {
                
            }
            
            self.people = fetchRequests
            
            
        }``` 
    

    相关文章

      网友评论

        本文标题:002 Core Data系列

        本文链接:https://www.haomeiwen.com/subject/rufdhttx.html