Search code examples
iosswiftwidgetnsuserdefaultsios-app-extension

How to share data (Array of custom objects) with today extension using NSUserDefaults?


Basically what I want to do is populate a UITableView in my today extension with objects stored in an array in my containing app.

I have been reading other answers that have to do with using NSUserDefaults to share data between a containing app and its extension and I found out that you cannot store an array of custom objects in NSUserDefaults. This is the code I've tried so far:

let group = "myGroupName"
        let sharedDefaults = NSUserDefaults(suiteName: group)
        sharedDefaults.setObject(MyArray, forKey: "Subjects")
        sharedDefaults.synchronize()

Obviously the above code doesn't work and I'm not sure if this is the correct way of doing it, Im still very new to this.

Any help would be much appreciated and if I'm going about this the wrong way please point me in the right direction.

edit
My Array is of type "subject" which is defined in a struct. it is made up of 3 strings (name, time1, time2) and UIColor (col)

struct subject{
var name = "un-named"
var time1 = "un-described"
var time2 = "un-described"
var col: UIColor = UIColor.whiteColor()}

class SubjectManager: NSObject{
var subjectsMonA = [subject]()
var subjectsTuesA = [subject]()
var subjectsWedA = [subject]()
var subjectsThursA = [subject]()
var subjectsFriA = [subject]()
var subjectsMonB = [subject]()
var subjectsTuesB = [subject]()
var subjectsWedB = [subject]()
var subjectsThursB = [subject]()
var subjectsFriB = [subject]()}

what i basically want to do is make the array "subjectsMonA" available to my Today Extension.


Solution

  • All you have to do is:

    var defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(array, forKey: "Subjects")
    

    and to retrieve it:

    var defaults = NSUserDefaults.standardUserDefaults()
    defaults.objectForKey("Subjects")
    

    Update

    Type struct is not a subclass of NSObject. Therefore NSUserDefaults won't except it as an object. I would suggest using an NSDictionary for your needs (because I don't know if you can insert a Swift Dictionary).

    var subject = NSDictionary() subject.setObject("un-named", forKey: "name") ...

    I apologize if the syntax is wrong I did that off the top of my head.