Question: Save contacts into tableview using core data


Save contacts into tableview using core data

Answers 1
Added at 2016-12-30 23:12

I have an app that uses the Contacts framework for iOS 9+. I have made a tableview that holds some selected contacts by the users. I want to be able to persist this list of contacts. what is the best way to do this? I was thinking of using core data.

My problem is that the contacts are "var Contacts = CNContact" hence are not of type NSManagedObject. I was under the impression that a to save data using core data the variables had to be of type NSManagedObject and my variables are of type CNContact.

Answers to

Save contacts into tableview using core data

nr: #1 dodano: 2016-12-31 19:12

Here's an example of using plists to hold your data. Lets say you have an object such as a "User". This user has a username and password for example.

Then in your user class you should have something like this:

class User: NSObject, NSCoding {

var username: String
var password: String

required init?(coder aDecoder: NSCoder) {
    username = aDecoder.decodeObject(forKey: "Username") as! String
    password = aDecoder.decodeObject(forKey: "Password") as! String

init(username: String, password: String, subjects: [Subject], colorPreferences: [Subject: UIColor], assessments: [Assessment]) {
    self.username = username
    self.password = password


func encode(with aCoder: NSCoder) {
    aCoder.encode(username, forKey: "Username")
    aCoder.encode(password, forKey: "Password")



Then what you need to do in a viewController, where you are using the user object is the following:

var loggedInUser: User?

class MyViewController: UIViewController {

func documentsDirectory() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    return paths[0]

func dataFilePath() -> String {
    return (documentsDirectory() as NSString).appendingPathComponent("AppInfo.plist") //name of your plist

func saveData() {

    let data = NSMutableData()
    let archiver = NSKeyedArchiver(forWritingWith: data)
    archiver.encodeObject(loggedInUser, forKey: "Logged In User") //whatever key you want
    data.write(toFile: dataFilePath(), atomically: true)


func loadData() {
    let path = dataFilePath()

    if FileManager.default.fileExists(atPath: path){

        if let data = NSData(contentsOfFile: path){

            let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
            loggedInUser = unarchiver.decodeObjectForKey("Logged In User") as? UserProfile




So this is a simplified version, but you should be able to adapt it to hold your list of CNContacts. Let me know if there are any issues. I use this code in my own apps so it should work just fine.

Source Show
◀ Wstecz