Swift how may I save contacts in defaults - swift

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

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.

Related

Retrieving array of custom objects from UserDefaults using NSKeyedUnarchiever in swift

I have saved an array of custom objects that conforms to NSCoding protocol in UserDefaults using NSKeyedArchiver. But when I try to retrieve it using NSKeyedUnarchiver, i get runtime errors from Xcode. I have tried initialising NSArray using unarchived data but it also failed. My guess is that while unarchiving swift doesn't understand custom elements of this array. How shall I do it?
This is how I archived array of custom objects
static func saveCategoryList(_ categoryList : [Category]!) -> Void{
let userDefaults = UserDefaults.standard
let categoryListData = NSKeyedArchiver.archivedData(withRootObject: categoryList)
userDefaults.set(categoryListData, forKey: Constants.CategoryList)
userDefaults.synchronize()
}
I get error like the attached screenshot in runtime. I am quite sure I am not doing it right. How can get my desired result?

How to unarchive data in swift 3?

I have an app where I save an array of CNContact to UserDefaults as such:
var contactsArray = [CNContact]()
let defaults = UserDefaults()
func (contact: CNContact){
contactsArray.append(contact)
let contactArrayArchive = NSKeyedArchiver.archivedData(withRootObject: contactArray) //archive the data
defaults.set(contactArrayArchive, forKey: "contactArray")
defaults.synchronize()
}
This archives the data to allow it to be saved to defaults. My issue is with how I can convert this data back to an array of CNContact in the viewDidLoad. I have seen many answers online which suggest to use NSKeyedArchiver.unarchiveObjectwithData but typing this into Xcode, with swift 3, says that the .unarchiveObjectwithData is not a member of NSKeyedArchiver. I keep looking for stuff about how to do this in swift 3 but have been unsuccessful. How can I unarchive the value?
You can use
NSKeyedUnarchiver.unarchiveObject(with: Data)
You have Used NSKeyedArchiver . You cannot use this to unarchive an Object.
If you press ⇧⌘0 to open the documentation and type nsk (3 characters are sufficient) you will see
To unarchive something you need the NSKeyedUnarchiver

App delegate has no member persistentStoreCoordinator (remove from core data, swift)

Hi I want to remove a row from core data. I was able to remove the item from the table, but not from core data. A lot of places give the same answer to this question. But after struggling for hours and seeing all links from the first 20 pages of google search results, it is still not working.
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete {
foodItems.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
}
let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext
let coord = delegate.persistentStoreCoordinator // App delegate has no member persistentStoreCoordinator
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try coord.executeRequest(deleteRequest, withContext: managedObjectContext)
} catch let error as NSError {
debugPrint(error)
}
}
I hope someone can help me. Thanks in advance.
The docs tell you how to update your in-memory objects: https://developer.apple.com/library/content/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html
make sure the resultType of the NSBatchDeleteRequest is set to NSBatchDeleteRequestResultType.resultTypeObjectIDs before the request is executed.
do {
let result = try moc.execute(request) as? NSBatchDeleteResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes = [NSDeletedObjectsKey : objectIDArray]
NSManagedObjectContext.mergeChangesFromRemoteContextSave(changes, [moc])
} catch {
fatalError("Failed to perform batch update: \(error)")
}
There are a few things going on here. You want to delete an entry. You need the managed object context, which you are already getting:
let managedObjectContext = delegate.persistentContainer.viewContext
You then appear to be trying to get an NSPersistentStoreCoordinator, which you don't need, and which causes your error message:
let coord = delegate.persistentStoreCoordinator // App delegate has no member persistentStoreCoordinator
You're getting this error message because your app delegate doesn't have a property called persistentStoreCoordinator. It's exactly as obvious as the error message sounds.
I'm not completely sure why you're trying to get a persistent store coordinator-- possibly because you're also trying to use a batch delete request even though you say you just want to delete a single row:
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ProductName")
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
If you run that request and it succeeds, you will delete every instance of ProductName, not just the one row. You're not telling the request to filter the objects and find only one (or a few). Instead you've set up a batch request that will hit every single instance instead of the selected row.
You could fix the batch request by adding a predicate, but that would be a very unusual way to delete a single row. Generally, you fetch a bunch of managed objects, and if you want to delete one, you tell the managed object to delete that object. There's no need for a batch request on a single object.
If your foodItems array contains instances of NSManagedObject (or subclasses of NSManagedObject), a better approach would be to use the managed object context, which has a delete method. Get the object at foodItems[indexPath.row] and pass it directly to the delete method.

Core Data - Change NSManagedObject array into array of Strings using valueForKey -OSX

So iv using an NSTokenField to allow data entry, the TokenField will suggest thing when the user starts typing. I want it to suggest things that are already inside core data.
To do this i have this function being called when the cell moves to superview (This is all happening inside a custom table view cell)
var subjectInformation = [NSManagedObject]()
let appDel = NSApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "SubjectInformation")
do {
let results = try context.executeFetchRequest(fetchRequest)
subjectInformation = results as! [NSManagedObject]
} catch {
}
this returns an array of NSManagedObjects, now i want for every object in managed object get get the valueForKey("subjectName") as insert it into a array of string so that i can return that inside this token field Function
func tokenField(tokenField: NSTokenField, completionsForSubstring substring: String, indexOfToken tokenIndex: Int, indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>) -> [AnyObject]? {
return subjectInformation //this is where is should return an array eg; ["English","Maths","Science"]
How would i do this? Thanks :)
If you properly subclassed your NSManagedObject you can use expressive Swift style filters and maps. You would cast your results array to [SubjectInformation] and
let subjectList = subjectInformation.map { $0.subjectName }
Try this:
(subjectInformation as! NSArray).valueForKeyPath("#unionOfObjects.subjectName")
This should return an array of the subjectNames of all the subjectInformation items.

NSInternalInconsistencyException: Invalid Update using tableview CoreData

I am using a tableView to display a list of people. I am trying to add an alert to confirm that the user actually wants to delete the person and to prevent mistakes. However, when I try to delete the person that is stored with CoreData, there seems to be a problem reloading the view. I get this exception:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (2) must be equal to the number of rows contained in that section before the update (2), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Editing and Delete Function:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
var deleteRow = indexPath.row
indexPathforDelete = indexPath
let entityDescription = NSEntityDescription.entityForName("People", inManagedObjectContext: managedObjectContext!)
let request = NSFetchRequest()
request.entity = entityDescription
var error: NSError?
var objects = managedObjectContext?.executeFetchRequest(request, error: &error)
if let results = objects {
let personToDelete = results[deleteRow] as! NSManagedObject
let firstName = personToDelete.valueForKey("firstName") as! String
let lastName = personToDelete.valueForKey("lastName") as! String
var message = "Are you sure you would like to delete \(firstName) \(lastName)?\nThis will permanentaly remove all records of "
if(personToDelete.valueForKey("gender") as! String == "Male"){
message = "\(message)him."
}
else{
println(personToDelete.valueForKey("gender") as! String)
message = "\(message)her."
}
var deleteAlert : UIAlertView = UIAlertView(title: "Delete \(firstName) \(lastName)", message: message, delegate: self, cancelButtonTitle: "Cancel")
deleteAlert.addButtonWithTitle("Delete")
deleteAlert.show()
}
save()
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
AlertView Response Function:
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){
if(buttonIndex == 1){
managedObjectContext?.deleteObject(personToDelete)
tableView.deleteRowsAtIndexPaths([indexPathforDelete], withRowAnimation: .Fade)
save()
}
setEditing(false, animated: true)
self.navigationItem.leftBarButtonItem = nil
}
tableView number of rows function:
var personToDelete = NSManagedObject()
var indexPathforDelete = NSIndexPath()
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
let entityDescription = NSEntityDescription.entityForName("People", inManagedObjectContext: managedObjectContext!)
let request = NSFetchRequest()
request.entity = entityDescription
var error: NSError?
var objects = managedObjectContext?.executeFetchRequest(request, error: &error)
let results = objects
println("Results Count: \(results!.count)")
return results!.count
}
I think the problem is that you have two variables with the name propertyToDelete: a property that you declare and initialise with a blank NSManagedObject:
var personToDelete = NSManagedObject()
and a local variable that you declare within your commitEditingStyle function:
let personToDelete = results[deleteRow] as! NSManagedObject
It is this local variable to which you assign the object from your results array. But this local variable is destroyed when the function completes, and the AlertView action is deleting the object to which the property points. (The reason I hesitate is that I would expect your context to throw an error when it tries to delete an object that has never been registered with it). Note that by contrast you have only the one variable named indexPathforDelete. This holds the correct value when the AlertView action runs, and consequently the tableView deletes the correct row. That's why you get the error: it has deleted a row, but then finds (because no object has been deleted) it still has the same number of rows as before.
The immediate solution is to use the property within your function, rather than a local variable: just delete let:
personToDelete = results[deleteRow] as! NSManagedObject
But I would also recommend rethinking your approach: you are repeating the same fetch. If all the datasource methods do the same, it will be repeated numerous times when the table view is first built, whenever a cell is scrolled into view, whenever a cell is tapped, etc. This will be costly in terms of performance. You should instead undertake the fetch once (perhaps in viewDidLoad), store the results in an array property, and use that for the table view datasource methods. Alternatively, and perhaps preferably, use an NSFetchedResultsController: it is very efficient and there is boilerplate code for updating the table view when objects are added or deleted.
The documentations of tableView:commitEditingStyle:forRowAtIndexPath: says: "You should not call setEditing:animated: within an implementation of this method. If for some reason you must, invoke it after a delay by using the performSelector:withObject:afterDelay: method."