11

I'm trying to change a Bool property and am receiving an EXC_BAD_ACCESS error.

I'm using XCode 6 and Swift.

The note property saves fine but the completed property throws the EXC_BAD_ACCESS error

enter image description here

import Foundation
import CoreData

class Task: NSManagedObject
{

    @NSManaged var note: String!
    @NSManaged var completed: Bool

}

Changing out the property routine

    // taskObject is an instance of Task()

    // Set the completed flag
    taskObject.completed = true // EXC_BAD_ACCESS
vutran
  • 887
  • 8
  • 19
  • 2
    I would try using `NSNumber(bool:true)` instead of `true`. CoreData is based on sqlite which does not have a bool type, it uses 0/1 numbers internally. – Abhi Beckert Jun 09 '14 at 00:52
  • This will product a type error since NSNumber doesn't follow the `@NSManaged completed: Bool` type – vutran Jun 09 '14 at 03:27
  • 2
    Your variable should be an `NSNumber` unless you explicitly checked "use scalar values for primitives" when creating your core data model file. – borrrden Jun 09 '14 at 03:54
  • Looks like changing that the data type to `NSNumber` in the subclass worked. – vutran Jun 09 '14 at 05:52
  • 1
    See this post, similar: http://stackoverflow.com/questions/24333507/swift-coredata-can-not-set-a-bool-on-nsmanagedobject-subclass-bug?lq=1 – iQ. Jun 23 '14 at 16:07

4 Answers4

2

Had the same problem, the solution is indeed to use NSNumber in the @NSManaged property. Additionally you could define a computed Bool property so that you can work with the scalar Boolean in your business logic and not with the NSNumber.

var isCompleted: Bool {
get {
    return completed == NSNumber(bool: true)
}
set {
    completed = NSNumber(bool: newValue)
}
}
Sterbic
  • 213
  • 5
  • 15
  • Hey, i have the same problem , but while retrieving the bool. It is stored as Integer while it shows of type bool in the modal. I need to show something based on the bool/integer value. Is this something that you know? `commentsList[indexPath.row].isSigned` gives Bad_access Exception. – Sashi Apr 06 '15 at 16:58
1

I'm just considering filing a bug as I have the same issue but if your really want to use Bool still then a workaround is to use this method:

setValue(true, forKey: "completed")
iQ.
  • 3,811
  • 6
  • 38
  • 57
1

I had almost this exactly problem.

Boolean works in Core Data.

The problem I had was in the Core Data Editor under 'CONFIGURATIONS' and 'C' Default. I did not have my entity linked to the correct class.

Mevdev
  • 334
  • 2
  • 7
1

You can use a swift Bool with an NSManagedObject - no need for the NSNumber nonsense. But you need to make sure that in the core data editor, the class is not empty. Enter your objects' name.

do not leave this empty

Jason Moore
  • 7,169
  • 1
  • 44
  • 45