1

I struggle for weeks with this Bug and hope someone can give me a hint.

I use a CoreDate relationship (One to Many) and CoreData generates a NSSet? for me:

@NSManaged public var builds: NSSet?

Now I try to convert this NSSet to an Array and sometimes get a

  malloc: double free for ptr 0x7fd48a008e00
  malloc: *** set a breakpoint in malloc_error_break to debug
  malloc: double free for ptr 0x7fd48a008e00
    public var buildsArray: [CBuild] {
>       let buildsArray =  builds.array(ofType: CBuild.self)
        return buildsArray.sorted {
                $0.number > $1.number
            }
    }

    extension Optional where Wrapped == NSSet {
        func array<T: Hashable>(ofType: T.Type) -> [T] {
             self?.allObjects as?  [T] ??  [T]()
        }
    }

I use only background threads to write in CoreData but SwiftUI is executing this lines on main Thread. I don't know if this is the problem?

appbieger
  • 11
  • 2
  • Does this answer your question? [Convert NSSet to Swift Array](https://stackoverflow.com/questions/24422831/convert-nsset-to-swift-array) – koen Jan 17 '22 at 12:38
  • unfortunately not, I tried the different ways of that example and the conversion works most of the time fine, but I still get sometimes my malloc_error and a crash even if I try to cast or map the set – appbieger Jan 17 '22 at 13:07
  • The problem is likely what you are trying to do with the set. Most of the time relationship objects are *faults*, you can "see" them but they are still in the store. CoreData decides when to actually pull them from the store. Use `NSPredicate`, sort descriptors instead of manual versions. `Array(object.relationship.allObjects)` is the "best" way to get array, you can't manipulate it from there just see/display the array itself. You have to use the add, create and delete methods provided. A CoreData relationship is not like a regular array in many way but it can be viewed like a regular array. – lorem ipsum Jan 17 '22 at 13:28
  • I tried to work with all objects like this: \`public var buildsArray: [CBuild] { if let buildObjects = self.builds?.allObjects as? [CBuild] { let buildsArray = Array(buildObjects) return buildsArray.sorted { $0.number > $1.number } } return [CBuild]() }` but now I got sometimes a EXC_BAD_ACCESS – appbieger Jan 17 '22 at 14:37
  • You can't sort a fault use a sort descriptor – lorem ipsum Jan 17 '22 at 15:21
  • sorting isn't the Problem. The the code throws the error as soon as I create the Array :/ – appbieger Jan 17 '22 at 15:58

0 Answers0