kiuzio2
kiuzio2

Reputation: 11

Storing NSDate as an array in CoreData

I am working on an app that requires storing time of taking pills. With notification action i want to store time of taking this pill in CoreData. Is this possible to use it as array like this ? My entity:

Core Data Attributes

And notification action:

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

Upvotes: 0

Views: 190

Answers (1)

Daniel Zhang
Daniel Zhang

Reputation: 5858

It is possible to store any type that conforms to NSCoding in a Core Data Transformable attribute by archiving it to NSData. Therefore, you can store your array in Core Data.

Here is an example for archiving the data in an attribute for a Core Data entity where myEntity is an NSManagedObject reference.

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

The data can be retrieved using the corresponding unarchive operation once you have a reference to the managed object such as one returned from a fetch request.

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

Upvotes: 1

Related Questions