lundi 23 mars 2015

Core Data is inserting blank objects

I am implementing core data in a new application but am having some very strange behaviour. When I call:



let newCard = NSEntityDescription.insertNewObjectForEntityForName("Card", inManagedObjectContext:context) as Card


and then print newCard I get nothing. It just leaves a space in console:


enter image description here


I am using the default Apple CoreData stack and here is the code for creating a new card:



class func createNewCardT(tempCard: TemporaryCard, managedContext: NSManagedObjectContext) {

// TODO: Find out which of these properties needs to be unique. For now I have chosen barcode only.
var request = NSFetchRequest()
let context = managedContext

var entity = NSEntityDescription.entityForName("Card", inManagedObjectContext: context)
let predicate = NSPredicate(format: "barcode = %@ && name = %@", tempCard.barcode, tempCard.name)
request.predicate = predicate
request.entity = entity

var error: NSError?
let count = context.countForFetchRequest(request, error: &error)

if error != nil {
println(error)
}
else if count > 0 {
println()
}
else {
// If no error and the count is not >0 then we can create a new card.

let newCard = NSEntityDescription.insertNewObjectForEntityForName("Card", inManagedObjectContext:context) as Card

println("Before I print new card")

println(newCard)

println("After I print new card")

newCard.name = tempCard.name
newCard.desc = tempCard.desc
newCard.frontPhoto = tempCard.frontPhoto
newCard.backPhoto = tempCard.backPhoto
newCard.barcode = tempCard.barcode


if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
}


}


Also if I create the same card again it actually finds it. i.e the count return from context.countForFetchRequest(request, error: &error) is equal to one.


And if I actually make the fetch request with the predicate in the code it returns an array with an empty object like so. I don't understand how the predicate can return something when there seems to be no object there:


enter image description here


I have also download the database off the device and opened it in firefox SQLite manager and the tables are empty.


If you need anymore information please don't hesitate to ask.


Aucun commentaire:

Enregistrer un commentaire