关于Coredata" IN" &安培; "不在"

时间:2013-06-20 08:56:13

标签: core-data

SQL语句   SELECT * FROM TABLE WHERE ACTION IN('A','B');

以下代码抛出异常

- (NSArray*) fetchManagedObjects:(NSString*)className withFlag:(NSString*)flag{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:className inManagedObjectContext:[self managedObjectContext]];
    fetchRequest.entity = entity;
    NSMutableString *str = [NSMutableString stringWithFormat:@" ( 1== 1 ) "];
    if ([className isEqualToString:@"Entity3"]) {
        [str appendFormat:@" AND ( kfollowAction IN ('%@')  ) ", flag];
    }
    NSPredicate *predicate = [NSPredicate predicateWithFormat:str];
    fetchRequest.predicate = predicate;
    NSError *error = nil;
    NSArray *entities = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    return entities;
}
  

2013-06-20 16:45:51.318 CNPL [1447:1a903] *终止应用程序   未捕获的异常'NSInvalidArgumentException',原因:   ' - [__ NSCFString countByEnumeratingWithState:objects:count:]:   无法识别的选择器发送到实例0x16965b30'   * 第一次抛出调用堆栈:(0x3647012 0x2ea2e7e 0x36d24bd 0x3636bbc 0x363694e 0x192966c 0x1928e06 0x191b829 0x191ad08 0x1915915 0x19155f2   0x19153c0 0x1915195 0x1914977 0x1914464 0x19135dd 0x1911539 0xdce02   0xe261a 0x1ec81c7 0x1ec8232 0x1ec84da 0x1edf8e5 0x1edf9cb 0x1edfc76   0x1edfd71 0x1ee089b 0x1ee0e93 0x1ee0a88 0xe1dd3 0x2eb6705 0x1dea2c0   0x1dea258 0x1eab021 0x1eab57f 0x1eaa6e8 0x1e19cef 0x1e19f02 0x1df7d4a   0x1de9698 0x3909df9 0x3909ad0 0x35bcbf5 0x35bc962 0x35edbb6 0x35ecf44   0x35ece1b 0x39087e3 0x3908668 0x1de6ffc 0x1ab1a 0x2f35)

如何使用Coredata?

1 个答案:

答案 0 :(得分:2)

首先: 从不 使用stringWithFormat来构建谓词。格式说明符 引用在stringWithFormatpredicateWithFormat中的工作方式不同,因此使用字符串 谓词的格式化函数非常容易出错。 如果必须在运行时组合谓词, 使用NSCompoundPredicate中的方法。

现在选择“kfollowAction”属性具有给定列表中的一个值的对象, 你必须使用带有数组的“IN”运算符,例如:

NSArray *flags = @[@"A", @"B"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"kfollowAction IN %@", flags]; 

也不需要虚拟谓词“(1 == 1)”。如果要获取所有对象, 然后就不要为获取请求设置谓词。