2016-05-25 40 views
0

早上好,我按照這個教程 我能夠添加一個新的聯繫人並檢索現有的聯繫人,但我試圖完成的是保存列表,我添加在一個mutableArray並使用該數組來填充我的TableView。我得到這個錯誤Swift如何在默認情況下保存聯繫人

聯繫人簡介[5166:4971615] ***由於未捕獲異常'NSInvalidArgumentException',原因:'試圖插入非屬性列表對象( 「!$ _,value => \ 「\ n)的,emailAddresses =(\ n \」!$ _,值=> \ 「\ n)的,postalAddresses =(\ n)>」 )關鍵contactsKey」

這裏

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") 

    } 

任何幫助表示讚賞。

Regards JZ

+0

要以用戶默認值保存對象數組,對象必須是對屬性列表有效的類型。 (https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html)您可以使用聯繫人的「標識符」字符串(並在需要時查找聯繫人) ? –

回答

1

NSUserDefaultsproperty list支持,所以您只能添加對象屬性列表對象(see list of compatible objects here)。

CNContact不在該列表中,因此您無法直接將其添加到NSUserDefaults。解決此

一種方法是序列化/反序列化手動將CNContact對象弄成一個NSDictionaryNSDatalike in this answer)兼容然後你就可以保存到NSUserDefaults