我创建了 NSManagedObject 的类别,例如create、count等。除了以下之外,所有这些都可以找到
@interface NSManagedObject(ManagedObjectExtension)
+ (id)findWithPredicate:(id)stringOrPredicate, ...;
@end
@implementation NSManagedObject(ManagedObjectUtilities)
+ (id)findWithPredicate:(id)stringOrPredicate, ... {
NSFetchRequest *fetchRequest = [self allFetchRequest];
if (stringOrPredicate) {
NSPredicate *predicate;
if ([stringOrPredicate isKindOfClass:[NSString class]]) {
va_list variadicArguments;
va_start(variadicArguments, stringOrPredicate);
predicate = [NSPredicate predicateWithFormat:stringOrPredicate arguments:variadicArguments];
va_end(variadicArguments);
} else {
predicate = (NSPredicate *)stringOrPredicate;
}
[fetchRequest setPredicate:predicate];
}
NSError *error;
NSArray *results = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(@"%@", [error description]);
}
if ([results count] == 0) {
return nil;
} else if ([results count] == 1) {
return [results objectAtIndex:0];
} else {
return results;
}
}
@end
这些是结果
NSString *email = [NSString stringWithString:someTextField.text];
NSLog(@"%@", [User findWithPredicate:@"email == "%@", email]);
==> (null)
NSLog(@"%@", [User findWithPredicate:[NSString stringWithFormat:@"email == "%@", email]]);
==> "<User: 0x1d827e10> ..."
基本上,此方法仅在我发送字符串而不是格式化字符串和参数时才有效。如果我打印在此方法中创建的谓词,这些是结果
[User findWithPredicate:@"email == "%@", email];
==> email == "%@"
[User findWithPredicate:[NSString stringWithFormat:@"email == "%@", email]];
==> email == "tar.tw45@gmail.com"
你知道是什么原因造成的吗?欢迎任何意见或建议:)