我創建NSManagedObject的類別,如創建創建,計數和其他人。所有這些作品發現,除了以下NSPredicate與格式的va_list/NSArray的失敗,但成功的字符串
@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 == "[email protected]"
你知道什麼會導致這種情況嗎?任何意見或建議,歡迎:)
這是一個錯字:@「email ==」%@「 應該是:@」email =='%@'「 – kitschmaster 2013-02-09 07:49:12
@kitschmaster謝謝,這很簡單,因爲刪除單引號可以解決問題。 – 2013-02-10 16:51:37