谓词正在变为零,nscoredata,客观

时间:2014-03-21 16:15:57

标签: ios objective-c core-data nspredicate predicatewithformat

我正在做的是获取核心数据的数据

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];

然而,谓词的结果是零。但以下作品

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

如果您有任何想法,请提供帮助。欢迎所有评论。感谢

2 个答案:

答案 0 :(得分:2)

使用格式创建谓词将插入各种引号并更改所提供的参数,使其有效且适合使用。通过提供谓词的一部分作为参数,您可以使用此功能。

更改switch语句以创建完整格式字符串,但不插入任何参数。然后,使用该格式字符串和所需参数集创建谓词:

NSString *format;
id cubesParameter;

switch (typeCube) {
    case NewCubes: {
        format = @"type == %d AND (accounts.keyChainId == %@)";
        cubesParameter = NewCubes;
        break;
    }
    case AllCubes: {
        format = @"type != %d AND (accounts.keyChainId == %@)";
        cubesParameter = CustomCubes;
        break;
    }
    case CustomCubes: {
        format = @"type == %d AND (accounts.keyChainId == %@)";
        cubesParameter = CustomCubes;
        break;
    }
}

NSPredicate *predicate = [NSPredicate predicateWithFormat:format, cubesParameter, accountKeyChainId];

答案 1 :(得分:2)

有一个名为NSCompoundPredicate的类,它允许您使用AND,OR和NOT运算符构造谓词。在这里你需要

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

所以代码将是 -

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]];

在此处阅读有关NSCompountPredicates的更多信息:http://nshipster.com/nspredicate/