0

以下は私の検索または作成コードです:

+ (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 があります。. 私も使用してみました。entityIDKeyentityIDValueentityIDKey = entityIDValue==

使用する比較方法に関係なく、if ( [array count] )メソッドはヒットしないため、2 番目のNSLogステートメントは常に出力を取得し、Core Data ストアに存在することがわかっているオブジェクトが実際には存在しないことを示します。そのため、ストアのコンテンツを表示しようとすると、多くのエントリが重複してしまいます。

NSPredicate ステートメントは正しいですか?

    `NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@=%@", entityIDKey, entityIDValue];`

どこentityIDKey = @"userID"entityIDvalue = @"1234567890"

ありがとう!

4

1 に答える 1

0

うん、問題は間違いなく述語だった。

述語引数は次のようにする必要があります。

%K == %@

いいえ

%@ = %@

于 2012-05-25T18:14:04.157 に答える