0

我正在为核心数据获取数据的操作如下

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)

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

4

2 回答 2

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/

于 2014-03-21T16:23:25.537 回答
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];
于 2014-03-21T16:21:13.753 回答