A hard-to-catch iOS Core Data programming bug

Consider the following code:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"Post" 
                               inManagedObjectContext:context];
request.entity = entity;
request.fetchLimit = 0;
NSPredicate *pred = [NSPredicate 
                     predicateWithFormat:@"ANY followers.name CONTAINS[c] %@", username];
request.predicate = pred;
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

It works properly to retrieve a list of posts whose to-many relationship “followers” contains a user whose name contains “username” case-insentively. However, if the code was written carelessly as follow:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"Post" 
                               inManagedObjectContext:context];
request.entity = entity;
request.fetchLimit = 0;
NSPredicate *pred = [NSPredicate 
                     predicateWithFormat:@"ANY users.name CONTAINS[c] %@", username];
request.predicate = pred;
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];

If there is no to-many relationship “users” in the NSManagedObject “Post”, the app will crash with a EXC_BAD_ACCESS error and provide no useful traceback information. Without knowing exactly which line is causing the error, the programmer has to spend some time to carefully scan probably 50 lines of code (probably mixed with other Core Data code, such as NSExpression and NSExpressionDescription).

Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s