santi.gs
santi.gs

Reputation: 714

Converting NSSet to Swift Set causes memory error

I have a one-to-many CoreData relationship between entities: Book and NoteSection called sections_.

I am converting an NSSet created by core data to a swift Set using:

var sections: [NoteSection] {
    get {
        if let sections = sections_ as? Set<NoteSection> {
            return sections.sorted(by: { $0.order < $1.order })
        }
        return []
    }
    set {
        sections_ = NSSet(array: newValue)
    }
    
}

However, this seems to cause a memory error when the book has no NoteSections:

Error message

Is there a safer way to turn a NSSet into a Set and can anyone explain why this memory error happens? Thanks

Edit:

When printing sections_ at the beginning of the get. The console shows this:

Optional(Relationship 'sections_' fault on managed object (0x600000231db0) <Book: ...

Upvotes: 1

Views: 165

Answers (1)

NilsBerni
NilsBerni

Reputation: 71

This works for me as a getter. If possible you could try to to remove the set and save your NoteSection to the relationship.

public var objectsArray: [Object] {
    let set = objects as? Set<Object> ?? []
    return set.sorted {
       $0.id < $1.id
    }
}

Upvotes: 0

Related Questions