Search code examples
iosobjective-ccore-datanspredicatepredicatewithformat

predicate is getting nil, nscoredata, objective


What I am doing to fetch the data for core data is following

NSString *str;
NSPredicate *predicate;

switch (typeCube) {
    case NewCubes: {
        str = [NSString stringWithFormat:@"type == %d",NewCubes];
        break;
    }
    case AllCubes: {
        str = [NSString stringWithFormat:@"type != %d",CustomCubes];
        break;
    }
    case CustomCubes: {
        str = [NSString stringWithFormat:@"type == %d",CustomCubes];
        break;

    }
}

predicate = [NSPredicate predicateWithFormat:@"%@ AND (accounts.keyChainId == %@)", str, accountKeyChainId];

However, the result of predicate is nil. But the following works

predicate = [NSPredicate predicateWithFormat:@"(type == %d) AND (accounts.keyChainId == %@)", type, accountKeyChainId]; ( type is either NewCubes or AllCubes or CustomCubes)

Please help if you have any ideas. All comments are welcomed. Thanks


Solution

  • There is a class called NSCompoundPredicate which allows you to construct predicates with AND, OR and NOT operators. Here you need

    [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate2, etc.]];
    

    So the code will be --

    NSPredicate *predicate1;
    NSPredicate *predicate;
    
        switch (typeCube) {
            case NewCubes: {
                predicate1 = [NSPredicate predicateWithFormat:@"type == %d",NewCubes];
                break;
            }
            case AllCubes: {
                predicate1 = [NSPredicate predicateWithFormat:@"type != %d",CustomCubes];
                break;
            }
            case CustomCubes: {
                predicate1 = [NSPredicate predicateWithFormat:@"type == %d",CustomCubes];
                break;
    
            }
        }
        predicate = [NSPredicate predicateWithFormat:@"accounts.keyChainId == %@", accountKeyChainId];
        [NSCompoundPredicate andPredicateWithSubpredicates:@[predicate1, predicate]];
    

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