Saving and retrieving custom objects in Core Data - ios

It's the first time I'm trying to save and retrieve custom data to/from my core data, but I've run into an error saying:
fatal error: array cannot be bridged from Objective-C
when I try to load the data back.
My code looks like this, the arrayOfNames is declared as [String]:
#IBAction func saveTap(sender: AnyObject) {
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contxt: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Indexes", inManagedObjectContext: contxt)
let arrayData: NSData = NSKeyedArchiver.archivedDataWithRootObject(arrayOfNames)
let newIndex = Indexes(entity: en!, insertIntoManagedObjectContext: contxt)
newIndex.monday = arrayData
println(newIndex.monday)
contxt.save(nil)
}
#IBAction func loadTap(sender: AnyObject) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let fetchReq = NSFetchRequest(entityName: "Indexes")
let en = NSEntityDescription.entityForName("Indexes", inManagedObjectContext: context)
var myList:[String] = context.executeFetchRequest(fetchReq, error: nil) as! [String]
println(myList)
}
My model-file looks like this:
#objc(Indexes)
class Indexes: NSManagedObject {
#NSManaged var monday: NSData
#NSManaged var tuesday: NSData
#NSManaged var wednesday: NSData
#NSManaged var thursday: NSData
#NSManaged var friday: NSData
}
I've also set all the attributes to transformable in my data model. As I said, it's the first time I'm doing this, so sorry if the solution is obvious.
Any suggestions would be appreciated.

executeFetchRequest returns [AnyObject]?, not [String], indeed the objects in the array should be Indexes instances which contain your archived arrays of strings.
So, you need to correct the array type that the results of the fetch are being placed into.

Related

Fatal error: unexpectedly found nil while unwrapping an Optional value inside an entity

I want an UICollectionViewCell to be deleted when the delete button is tapped:
#IBAction func deleteButtonClicked() {
error here: delegate?.deleteTrigger(clothes!)
}
clothes:
var clothes: Clothes? {
didSet {
updateUI()
}
}
func deleteTrigger:
func deleteTrigger(clothes: Clothes){
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName("Category", inManagedObjectContext: context)
if let entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context) {
let indexPath = NSIndexPath()
//var cat : Category = clothing as! Category
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext: NSManagedObjectContext = appDelegate.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "Clothes")
let predicate = NSPredicate(format: "category == %#", self.selectedCategory!)
fetchRequest.predicate = predicate
var error: NSError? = nil
var clothesArray = managedContext.executeFetchRequest(fetchRequest, error: &error)!
managedContext.deleteObject(clothesArray[indexPath.row] as! NSManagedObject)
clothesArray.removeAtIndex(indexPath.row)
self.collectionView?.deleteItemsAtIndexPaths([indexPath])
if (!managedContext.save(&error)) {
abort()
}
}
Clothes is an entity in Core Data. Does anyone know why I am getting this error? I am trying to delete a collectionViewCell from core data with in a one-to-many relationship. Category is the parent entity and Clothes is the entity within the Category.
You have declared a property clothes:
var clothes: Clothes?
You never gave it any value, so it is nil. Thus when you force-unwrap it by saying clothes!, you crash.
As others said, your value is nil. You need to unwrap the variable before you can do anything with it. Try this:
#IBAction func deleteButtonClicked()
{
if var clothes = clothes
{
delegate?.deleteTrigger(clothes)
}
}

How to save Array to CoreData?

I need to save my array to Core Data.
let array = [8, 17.7, 18, 21, 0, 0, 34]
The values inside that array, and the number of values are variable.
1. What do I declare inside my NSManagedObject class?
class PBOStatistics: NSManagedObject, Equatable {
#NSManaged var date: NSDate
#NSManaged var average: NSNumber
#NSManaged var historicAverage: NSNumber
#NSManaged var total: NSNumber
#NSManaged var historicTotal: NSNumber
#NSManaged var ordersCount: NSNumber
#NSManaged var historicOrdersCount: NSNumber
#NSManaged var values: [Double] //is it ok?
#NSManaged var location: PBOLocation
}
2. What do I declare inside my .xcdatamodel?
3. How do I save this in my Entity? (I use MagicalRecord)
let statistics = (PBOStatistics.MR_createInContext(context) as! PBOStatistics)
statistics.values = [8, 17.7, 18, 21, 0, 0, 34] //is it enough?
Ok, I made some research and testing. Using Transformable type, solution is simple:
1. What do I declare inside my NSManagedObject class?
#NSManaged var values: [NSNumber] //[Double] also works
2. What do I declare inside my .xcdatamodel?
Transformable data type.
3. How do I save this in my Entity?
statistics!.values = [23, 45, 567.8, 123, 0, 0] //just this
“You can store an NSArray or an NSDictionary as a transformable attribute. This will use the NSCoding to serialize the array or dictionary to an NSData attribute (and appropriately deserialize it upon access)” - Source
Or If you want to declare it as Binary Data then read this simple article:
Swift 3
As we don't have the implementation files anymore as of Swift 3, what we have to do is going to the xcdatamodeld file, select the entity and the desired attribute (in this example it is called values).
Set it as transformable and its custom class to [Double]. Now use it as a normal array.
Convert Array to NSData
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("Device",
inManagedObjectContext:managedContext)
let device = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
let data = NSKeyedArchiver.archivedDataWithRootObject(Array)
device.setValue(data, forKey: "dataOfArray")
do {
try managedContext.save()
devices.append(device)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
Convert NSData to Array
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Device")
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
if results.count != 0 {
for result in results {
let data = result.valueForKey("dataOfArray") as! NSData
let unarchiveObject = NSKeyedUnarchiver.unarchiveObjectWithData(data)
let arrayObject = unarchiveObject as AnyObject! as! [[String: String]]
Array = arrayObject
}
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
For Example : https://github.com/kkvinokk/Event-Tracker
If keeping it simple and store an array as a string
Try this:
// Array of Strings
let array: [String] = ["red", "green", "blue"]
let arrayAsString: String = array.description
let stringAsData = arrayAsString.data(using: String.Encoding.utf16)
let arrayBack: [String] = try! JSONDecoder().decode([String].self, from: stringAsData!)
For other data types respectively:
// Set of Doubles
let set: Set<Double> = [1, 2.0, 3]
let setAsString: String = set.description
let setStringAsData = setAsString.data(using: String.Encoding.utf16)
let setBack: Set<Double> = try! JSONDecoder().decode(Set<Double>.self, from: setStringAsData!)
Make entity attribute type as "Binary Data"
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:TheArray];
myEntity.arrayProperty = arrayData;
[self saveContext]; //Self if we are in the model class
Retrive original array as:
NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:anEntity.arrayProperty];
That's all.
Following code works for me to store array of JSON in CoreData
func saveLocation(model: [HomeModel],id: String){
let newUser = NSEntityDescription.insertNewObject(forEntityName: "HomeLocationModel", into: context)
do{
var dictArray = [[String: Any]]()
for i in 0..<model.count{
let dict = model[i].dictionaryRepresentation()
dictArray.append(dict)
}
let data = NSKeyedArchiver.archivedData(withRootObject: dictArray)
newUser.setValue(data, forKey: "locations")
newUser.setValue(id, forKey: "id")
try context.save()
}catch {
print("failure")
}
}

IOS - AnyObject is not convertible to String when loading core data into a table view?

I use Swift. I can save data into a core data base. And I can even print out the data in a for loop but I can't load it into a table view. I have an empty string array(called subjects) that the table view uses it as a data source but I would like to load the data in a for loop into that array.
Here's how I save the data:
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var newSubject = NSEntityDescription.insertNewObjectForEntityForName("Subjects", inManagedObjectContext: context) as NSManagedObject
newSubject.setValue("" + classTextField.text, forKey: "subjectName")
context.save(nil)
Here's how I retrieve the data:
I have an empty string array in the class called subjects.
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Subjects")
request.returnsObjectsAsFaults = false
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if(results.count > 0){
for res in results{
println(res)
subjects.append(res)
}
}else{
println("0 Results.")
}
So, I can print out the data as you can see in the for loop, but I can't add that res value into my subjects array which is used by the table view. But I get the AnyObject is not convertible to String error message.
Edit:
Sorry, I misunderstood the code.
You need to unwrap the results to an array of Subjects
if let resultsUnwrapped = results as? [Subjects] {
for res in resultsUnwrapped{
println(res.description())
subjects.append(res.subjectName)
}
}

One to many relationship CoreData Swift

Core Data works great for the most part. When I click on name first VC (Items) and performSeque to the second VC (Costs), I can see the costsName and other data. But when I add second name in first VC I can see the same data as in first name.
I'm trying to make a one to many relationship.
I have 2 data models:
import Foundation
import CoreData
#objc(Items)
class Items: NSManagedObject {
#NSManaged var count: NSNumber
#NSManaged var name: String
#NSManaged var cost: NSSet
}
import Foundation
import CoreData
#objc(Costs)
class Costs: NSManagedObject {
#NSManaged var costsDate: NSDate
#NSManaged var costsName: String
#NSManaged var costsValue: NSNumber
#NSManaged var account: Items
}
Here is addAccount's (name of the first VC) save action:
#IBAction func saveButtonPressed(sender: UIBarButtonItem) {
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Items", inManagedObjectContext: managedObjectContext!)
let account = Items(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
account.name = cellOneNameTextField.text
if cellTwoCountTextField.text.isEmpty {
} else {
account.count = (cellTwoCountTextField.text).toInt()!
}
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Items")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
self.navigationController?.popViewControllerAnimated(true)
}
Here is addCost's save action:
#IBAction func saveButtonTapped(sender: UIBarButtonItem) {
// CoreData Access
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Costs", inManagedObjectContext: managedObjectContext!)
let cost = Costs(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
cost.costsName = cellThreeNoteTextField.text
cost.costsValue = (cellOnePriceTextField.text).toInt()!
cost.costsDate = datePicker.date
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Costs")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
for res in results {
println(res)
}
delegate?.refreshTable()
self.navigationController?.popViewControllerAnimated(true)
}
I don't know if you do it somewhere, but your Items should attach a Count object to itself using your cost variable from your Items. Something like :
let account = Items(...)
let cost = Cost(...)
account.cost.addObject(cost)//and changing your var cost:NSSet into var cost:NSMutableSet
//then save Items
(I haven't tried the addObject but you understand the principle)

populate NSMutableArray using the CoreData database

Im trying to populate an NSMutableArray from the CoreData database (using swift) but not sure what I'm doing wrong. Here's my code:
var stuff: NSMutableArray = []
populating the NSMutableArray:
override func viewDidAppear(animated: Bool) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
let freq = NSFetchRequest(entityName: "MyData")
stuff = context.executeFetchRequest(freq, error: nil)
tableView.reloadData()
}
Error:
Just define stuff as
var stuff : Array<AnyObject> = []
Which will create stuff as an array suitable for the return type of executeFetchRequest().
When you then access elements of the array you will also need to satisfy the type constraints. You should look into the Apple documentation for as, as? and is and the associated usage examples. In the very simplest case it would be something like:
var aThing : NSManagedObject? = stuff[0] as? NSManagedObject
For the above aThing would be nil if stuff[0] is not an NSManagedObject nor subclasses.

Resources