Core Data
BOOL predicate
iOS development
Swift programming
data modeling

How to write a BOOL predicate in Core Data?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Core Data is Apple's framework for managing object graphs and persisting data in an iOS or macOS application. One common use case in Core Data is filtering objects based on properties, and BOOL predicates are frequently used to filter objects where a Boolean value is involved. This article explores how to write and utilize BOOL predicates in Core Data effectively.

Understanding Predicates

In Core Data, predicates are used for filtering data when fetching or updating records. A predicate is a logical condition applied to attribute values of managed objects, and it returns a Boolean value indicating whether the condition is true for those objects.

Essential Components of Predicates

  1. Predicate Format String: This is a format string used to define the logical condition. For example, @"age > 30" filters objects where their age property is greater than 30.
  2. Placeholder Variables: These are variables that can be replaced with actual values during runtime, allowing dynamic predicates.
  3. Operators: These are logical and comparison operators like >, <, ==, !=, AND, OR, etc.

BOOL Predicate Syntax

Boolean attributes in Core Data are typically represented as integers (NSNumber) rather than actual Boolean values. This is due to the Objective-C representation of Booleans and their storage in Core Data's SQLite backend.

Writing BOOL Predicates

To filter objects with a Boolean attribute, you use the Core Data predicate syntax to compare the attribute with YES or NO. Below is an example of how to write a BOOL predicate when fetching data:

  • NSFetchRequest: Represents a request to fetch data from a Core Data store. The entity name corresponds to the Core Data model entity.
  • NSPredicate: Used to define the filter criteria. The predicateWithFormat:"isFlagged == %@" specifies that the objects should have the isFlagged attribute set to YES.
  • @(YES) or NSNumber(booleanLiteral: true): Converts a Boolean value to NSNumber, as Core Data stores Boolean attributes as numeric values for compatibility reasons.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.