2015-11-13 43 views
0

我正在研究一個需要存儲服用藥丸時間的應用程序。隨着通知行動,我想存儲在CoreData服用此藥的時間。這可能像這樣使用它作爲數組嗎?我的實體:在CoreData中存儲NSDate作爲數組

Core Data Attributes

和通知動作:

func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler:() -> Void) { 
    if identifier == "remindLater" { 

     print("remindLater") 
     notification.fireDate = NSDate().dateByAddingTimeInterval(60) 
     UIApplication.sharedApplication().scheduleLocalNotification(notification) 

    } else if identifier == "takePill" { 

     print("Pill taken") 

     do { 
      let results = try managedObjectContext.executeFetchRequest(fetchRequest) 

      for medicine in results { 

       medicine.timeArray.append(NSDate()) 

      } 

     } catch let error as NSError { 
      print(error.userInfo) 
     } 


    } 

    completionHandler() 
} 

回答

1

它可以存儲由它歸檔到NSData的符合NSCoding在覈心數據可轉換屬性的任何類型。 因此,您可以將數組存儲在Core Data中。

下面是一個歸檔核心數據實體屬性中的數據的示例,其中myEntityNSManagedObject引用。

myEntity.setValue(NSKeyedArchiver.archivedDataWithRootObject(timeArray), 
        forKey: "timeArray") 

數據可利用相應的取消歸檔操作,一旦你必須被管理對象,例如一個從一個讀取請求返回的參照被檢索。

let myTimeArray = NSKeyedUnarchiver.unarchiveObjectWithData(
    myNSManagedObject.valueForKey("timeArray") as! NSData)