以下は私の検索または作成コードです:
+ (id)checkIfEntity:(NSString *)entityName
withIDValue:(NSString *)entityIDValue
forIDKey:(NSString *)entityIDKey
existsInContext:(NSManagedObjectContext *)context
{
// Create fetch request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setReturnsObjectsAsFaults:NO];
// Fetch messages data
NSEntityDescription *description = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];
[request setEntity:description];
// Only include objects that exist (i.e. entityIDKey and entityIDValue's must exist)
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@=%@", entityIDKey, entityIDValue];
[request setPredicate:predicate];
// Execute request that returns array of dashboardEntrys
NSArray *array = [context executeFetchRequest:request error:nil];
if ( [array count] ) {
NSLog(@"%@ = %@ DOES EXIST", entityIDKey, entityIDValue);
return [array objectAtIndex:0];
}
NSLog(@"%@ = %@ DOES NOT EXIST", entityIDKey, entityIDValue);
return [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
}
2 つの return ステートメントを使用してベスト プラクティスを採用していないという事実を無視してください。これは、コードを運用環境にプッシュする前に行います。
NSManagedObject エンティティに with を渡すことで機能し、 with 値entityName
があるかどうかをチェックする NSPredicate があります。. 私も使用してみました。entityIDKey
entityIDValue
entityIDKey = entityIDValue
==
使用する比較方法に関係なく、if ( [array count] )
メソッドはヒットしないため、2 番目のNSLog
ステートメントは常に出力を取得し、Core Data ストアに存在することがわかっているオブジェクトが実際には存在しないことを示します。そのため、ストアのコンテンツを表示しようとすると、多くのエントリが重複してしまいます。
NSPredicate ステートメントは正しいですか?
`NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@=%@", entityIDKey, entityIDValue];`
どこentityIDKey = @"userID"
とentityIDvalue = @"1234567890"
ありがとう!