Iva Horn

Notes from a software engineer for iPhone, iPad and Mac apps.

Memoji

Convenient NSPredicate Initializers

February 22, 2024 • #CoreData #Note #Swift

There is a better way than to repeat the same or similar NSPredicate all the time and it is very nice to read.

It actually is very simple but also hard to get as an idea, if you are caught up in routines. Basically, it only is an extension to NSPredicate which adds either static computed properties or methods to provide a new instance.

import Foundation

extension NSPredicate {
    static var softlyDeletedItemsOnly: NSPredicate {
        NSCompoundPredicate(orPredicateWithSubpredicates: [
            NSPredicate(format: "deletedByServer != nil"),
            NSPredicate(format: "deletedBySystem != nil"),
        ])
    }
}

In later use it results in a very neat and concise code.

let request: NSFetchRequest = Item.fetchRequest()
request.predicate = .softlyDeletedItemsOnly

This is just a very basic example. I think it becomes more obvious in programmatic composition of more complex predicates.

Of course there are is the new predicate macro in SwiftData which is much better but as explained earlier, I have to stick (mainly) to CoreData in my current project, for now.