1
votes

Basically as the title says.

I'm trying to fetch 'Goal's which have a 'tags' attribute of type string array, where 'tags' contains some tag of type string.

I have in the init() of the SwiftUI view

self.tag = tag

self.results = FetchRequest(
            entity: Goal.entity(),
            sortDescriptors: [NSSortDescriptor(keyPath: \Goal.createdDate, ascending: true)],
            predicate: NSPredicate(format: "tags LIKE %@", "\(self.tag.wrappedTitle)")

LIKE doesn't throw an error but also doesn't fetch anything even though it should.
CONTAINS throws an EXC_BAD_ACCESS error,
IN throws 'NSInvalidArgumentException', reason: '-[NSTaggedPointerString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xa6a3cbf31284b686'. Not quite sure what this error means.

I can fetch all goals and only display ones where tags contains the string within a ForEach loop in the view body, but I don't believe this is efficient memory usage.

For reference, Goal interface

public class Goal : NSManagedObject, Identifiable {
}

extension Goal {

    @NSManaged public var id: UUID? { get set }

    @NSManaged public var title: String? { get set }

    @NSManaged public var notes: String? { get set }

    @NSManaged public var tags: [String]? { get set }

    @NSManaged public var createdDate: Date? { get set }

    @NSManaged public var deadlineDate: Date? { get set }

    @NSManaged public var completedDate: Date? { get set }

    @NSManaged public var isActive: Bool { get set }

    @NSManaged public var isArchived: Bool { get set }

    @NSManaged public var previousIterations: [UUID]? { get set }

    @NSManaged public var hasBeenDeleted: Bool { get set }

    @NSManaged public var deletedDate: Date? { get set }
}

Can anyone help?

EDIT: as rightly pointed out in replies, it is not possible to dynamically filter a transformable data type :( workaround is to fetch all and filter within function.

1
Would you show auto-generated interface for Goal? - Asperi
Sure. Added now. - rskw00
Because tags is a transformable attribute, it is not possible to use a predicate based on it as part of the fetch request. There are workarounds, but I would recommend replacing it with a to-many relationship to a Tag entity (probably with a to-many inverse). - pbasdf

1 Answers

0
votes

You can try:

NSPredicate(format: "%@ IN tags", "\(self.tag.wrappedTitle)")