Question

I just faced with some issue that is connected to clear code. I use predicates in many modules of my projects. When I work with core data the NSPredicates are really helpful for retrieving filtered object.

But the predicating is good for logic but not for code readability as I use it.

So let's see on this example:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"(ANY option.playerzoneID == %d) \
                              AND (ANY option.gameId == %@) \
                              AND (team.teamID == %@) \
                              AND (league.leagueID == %@) \",
                              zoneIdType,
                              SELECTED_GAME.gameID,
                              SELECTED_TEAM.teamID,
                              SELECTED_LEAGUE.leagueID];

When I look on this predicate I am little confused about this structure even in case that this predicate I have written one week ago.

Any suggestion how to make this code more readable?

I think it will be better to have something like this:

[predicate setParametr:@"gameID == %@", SELECTED_GAME.gameID];
[predicate setParametr:@"league.leagueID == %@", SELECTED_LEAGUE.leagueID];
Was it helpful?

Solution

You can explore the following:

+ (NSPredicate *)andPredicateWithSubpredicates:(NSArray *)subpredicates
+ (NSPredicate *)orPredicateWithSubpredicates:(NSArray *)subpredicates
+ (NSPredicate *)notPredicateWithSubpredicate:(NSArray *)subpredicate

With this you can actually form short predicates and join them together with arrays. So, you don't exactly get what you wished for, but its a near shot.

NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"(ANY option.playerzoneID == %d)", zoneIdType];
NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"(ANY option.gameId == %d)", SELECTED_GAME.gameID];
NSPredicate *predicate3 = [NSPredicate predicateWithFormat:@"(ANY team.teamID == %@)", SELECTED_TEAM.teamID];

NSCompoundPredicate *compoundANDPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2, predicate3]];

Read more about these here:http://nshipster.com/nspredicate/

Edit: Using OR Predicates along with AND Predicates:


Let's assume: you have this predicate to add as OR:

NSPredicate *predicate4 = [NSPredicate predicateWithFormat:@"(ANY team.teamName == %@)", SELECTED_TEAM.teamName];

So, you can group your AND and OR predicates into one compound predicate (compoundANDPredicate as shown above) and then use

+ (NSPredicate *)orPredicateWithSubpredicates:(NSArray *)subpredicates

So it becomes:

[NSCompoundPredicate orPredicateWithSubpredicates:@[compoundANDPredicate, predicate4]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top