简体   繁体   中英

Save contacts into tableview using core data

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.

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
    archiver.finishEncoding()
    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

            unarchiver.finishDecoding()
        }

    }
}

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM