Alex Stone
Alex Stone

Reputation: 47354

iOS how to create NSPredicate with custom object key?

I'm building a game and have a spell class. Within this class there's a list of active instances of this spell. I'm trying to check if this spell has already been cast on some target by using a predicate: target == %@ . However, the code below does not return any objects.

How can I check if a key is equal to a custom object within a predicate?

   -(BOOL)checkHasUniqueInstanceWithModel:(CharacterModelNode*)targetModel
    {
        NSPredicate *uniqueSkillInstancePredicate =
 [NSPredicate predicateWithFormat:@"target == %@", targetModel];



        NSArray *results = [self.activeInstances filteredArrayUsingPredicate:uniqueSkillInstancePredicate];

        if(results.count == 0)
        {
            return NO;
        }else if(results.count == 1)
        {
            return YES;
        }else
        {
            NSAssert(false,@"Duplicate unique instance with skill: %@ on target: %@",self.name,targetModel.character.name);
        }
        return NO;
    }

Upvotes: 0

Views: 1489

Answers (1)

Putz1103
Putz1103

Reputation: 6211

Use a predicate with block:

NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(Spell* evaluatedObject, NSDictionary *bindings) {
    if([evaluatedObject.target isEqual: targetModel])
    {
        return true;
    }
    return false;
}];

NSArray *results = [self.activeInstances filteredArrayUsingPredicate:pred ];

Upvotes: 1

Related Questions