NSPredicate with Core Data

Displaying Core Data, data?

Want to display your data stored in Swift’s Object Graph framework? With it was more like SQL?

Read on for some great uses that might just improve your core skill.

This contains a full repo with the code, to follow along you can link at the bottom of this post.

Terminology

  • Core Data: A framework that allows you to manage the model layer objects in your application. Core Data does this by being an object graph management and persistance framework.
  • NSPredicate: Specifies how data should be displayed or filtered, much like a combination between a SQL WHERE clause and a regular expression.

Fetch all records

Single condition

Multi table condition

Retrieve records

Update

Delete all records

Delete all records with condition

Insert

Batch update

Batch operations

While doing batch operations there are potential issues:

  • Property validation is not performed on new values
  • Referential integrity is not maintained between related values
  • Merge conflicts can be introduced, so yourNSManagedObjectContext requires to have a policy
  • NSManagedObjects already in a NSManagedObjectContext are not automatically refreshed

Did you Know:

If a fetch request requires a compound predicate, it will be performant if you put the most restrictive predicate first. It is a simple performance optimisation, but one worth taking into account for your code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store