-1

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”*第一个throw call stack: (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)

如何使用核心数据?

4

1 回答 1

2

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

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

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

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

于 2013-06-20T09:24:20.953 回答