2017-10-13 71 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