簡體   English   中英

將NSDate作為數組存儲在CoreData中

[英]Storing NSDate as an array in CoreData

我正在開發一個需要存儲服葯時間的應用程序。 通過通知操作,我想將服用CoreData時間存儲在CoreData 這樣可以將其用作數組嗎? 我的實體:

核心數據屬性

和通知動作:

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()
}

通過將符合NSCoding的任何類型歸檔到NSData,可以將其存儲在Core Data Transformable屬性中。 因此,您可以將陣列存儲在Core Data中。

這是一個在Core Data實體的屬性中存檔數據的示例,其中myEntityNSManagedObject引用。

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

一旦您擁有對托管對象的引用(例如從提取請求返回的引用),就可以使用相應的非歸檔操作來檢索數據。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM