2017-10-13 74 views
0

我正在开发我的应用程序中的核心数据。 我想从核心数据中获取名称属性。从coredata中提取特定属性swift

类的ViewController:UIViewController的{

@IBOutlet weak var saveDataBtn:UIButton! 
@IBOutlet weak var dataTxtField:UITextField! 
@IBOutlet weak var dataLbl:UILabel! 
var tasks: [Task] = [] 
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

@IBAction func saveDataBtnPressed(_sender : UIButton){ 
    print("Save Data.") 
    let task = Task(context: context) 
    task.name = dataTxtField.text 
    (UIApplication.shared.delegate as! AppDelegate).saveContext() 
    getData() 
} 

func getData(){ 
    do{ 
     tasks = try context.fetch(Task.fetchRequest()) 

    }catch{ 
     print("Fetching Failed") 

    } 

} 

I am attaching my xcdatamodel

我怎样才能得到它呢?

谢谢,

+0

获取您感兴趣的Task对象并读取其“name”属性。 –

+0

我已经获取任务对象。但我无法读取名称属性 – user12346

+0

您能否让我知道如何从任务对象获取名称属性 – user12346

回答

1

在Swift 4中,您可以直接访问属性。

do { 
    let tasks = try context.fetch(request) 
    for task in tasks { 
     print(task.name) 
    } 
} catch let error { 
    print(error.localizedDescription) 
} 

修订 - 如何删除和更新实体的实例。

这里有一些想法来组织代码来处理更新和删除。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

extension Task { 
    // to get an instance with specific name 
    class func instance(with name: String) -> Task? { 
     let request = Task.fetchRequest() 

     // create an NSPredicate to get the instance you want to make change 
     let predicate = NSPredicate(format: "name = %@", name) 
     request.predicate = predicate 

     do { 
      let tasks = try context.fetch(request) 
      return tasks.first 
     } catch let error { 
      print(error.localizedDescription) 
      return nil 
     } 
    } 

    // to update an instance with specific name 
    func updateName(with name: String) { 
     self.name = name 
     (UIApplication.shared.delegate as! AppDelegate).saveContext() 
    } 

    // to delete an instance 
    func delete() { 
     context.delete(self) 
     (UIApplication.shared.delegate as! AppDelegate).saveContext() 
    } 
} 

func howItWorks() { 
    guard let task = Task.instance(with: "a task's name") else { return } 
    task.updateName(with: "the new name") 
    task.delete() 
} 
+0

谢谢!它得到了工作:) – user12346

+0

你有想要更新和删除特定的行在迅速4? – user12346

+0

我已经更新了答案。但我仍然建议阅读这个,https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index.html。 – mrfour