2

I have an NSData object stored in my core data. I want to be able to check if it exist or not using an if statement. I can't seem to work it out. I have the variable set up as:

var coreImage : NSData?

and I have tried using:

if (coreImage != nil) {

            println("Use core image")

        }else {

           println("Do something else")

}

I know I have NSData stored in core data but it never runs the if statement as I want it too so I must be doing something wrong?

Can anyone help?

Thanks.

  • the if check should work if you are getting a non nil value in coreImage – rakeshbs Jan 17 '15 at 15:37
  • Did you let Xcode create the NSManagedObject subclass file or did you write it yourself? It should be `@NSManaged var coreImage: NSData` for a "Binary Data" attribute. – Martin R Jan 17 '15 at 15:49
  • If you don't assign anything to your coreImage variable, it will be equal to nil, so it's not surprising that the code in your if statement never gets called. – Pop Flamingo Jan 17 '15 at 15:51
  • If your question is how to check if an *optional Core Data property* has been set or not, then this might help: http://stackoverflow.com/questions/25661120/check-if-property-is-set-in-core-data. – Martin R Jan 17 '15 at 15:51

2 Answers2

11

Check if NSData's length is > 0, that's it. Example:

if (coreImage.length > 0) {
//we're cool
}
Vivienne Fosh
  • 1,751
  • 17
  • 24
0

I am newer to Swift than you, but I think you need to do some special work to access and utilize items from Core Data. Try something like this:

let fetchRequest = NSFetchRequest(entityName: "coreImage")
if let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSData] {  
   println("Use core image")    
} else {
   println("Do something else")
}
Vidya
  • 29,932
  • 7
  • 42
  • 70
  • it is not about CoreData at all – Vivienne Fosh Mar 08 '16 at 21:09
  • I'm not sure that my answer is actually wrong, so the downvote violates the rules. But let's say it is. In that case, please provide what the question *is* about to help future readers. To provide no solution is lazy and unhelpful. – Vidya Mar 08 '16 at 22:40