0

Good morning all, I followed this tutorial I am able to add a new contact and retrieve existing contacts , but what I am trying to accomplish is save the list that I add in a mutableArray and use that array to populate my TableView. I am getting this error

Contacts Introduction[5166:4971615] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object ( "!$_, value=>\"\n), emailAddresses=(\n \"!$_, value=>\"\n), postalAddresses=(\n)>" ) for key contactsKey'

Here

 func insertNewObject(sender: NSNotification) {

        print("How Many Times am I getting here ??")

        if let contact = sender.userInfo?["contactToAdd"] as? CNContact {
            objects.insert(contact, atIndex: 0)
            let indexPath = NSIndexPath(forRow: 0, inSection: 0)
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
        }

        print("How Many Objects ",objects.count)

        let contactArray = objects as [CNContact]
        let prefs = NSUserDefaults.standardUserDefaults()
        prefs.setValue(contactArray, forKey: "contactsKey")

    }

Any Help is appreciated.

Regards JZ

John Z
  • 125
  • 1
  • 13
  • To save an array of objects in user defaults, the objects have to be types that are valid for a property list. (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html) Can you use the contact's `identifier` string instead (and look up the contact when you need it)? – Phillip Mills May 25 '16 at 17:40

1 Answers1

1

NSUserDefaults is backed by a property list, so you can only add objects to it that are property list objects (see list of compatible objects here).

CNContact is not on that list, so you can't add it to NSUserDefaults directly.

One way around this is to serialize/deserialize the CNContact object manually into something compatible like an NSDictionary or NSData (like in this answer) which you can then save to NSUserDefaults.

Community
  • 1
  • 1
nebs
  • 4,939
  • 9
  • 41
  • 70