2014-11-21 91 views
0

我從服務器獲取一個字符串,並且需要將其轉換爲State對象,該對象是NSManagedObject的子類。變壓器工作正常,但我不知道在映射時ManagedObjectContext是什麼,所以我得到錯誤illegal attempt to establish a relationship 'state' between objects in different contexts如何使用RKValueTransformer將NSString轉換爲核心數據NSManagedObject

RKEntityMapping知道如何在映射操作期間自動創建適當的對象,因此該功能位於RestKit中。我如何正確創建這個核心數據對象?

RKValueTransformer *stateTransformer = [RKBlockValueTransformer valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class sourceClass, __unsafe_unretained Class destinationClass) { 
    return ([sourceClass isSubclassOfClass:[NSString class]] && [destinationClass isSubclassOfClass:[State class]]); 
} transformationBlock:^BOOL(id inputValue, __autoreleasing id *outputValue, Class outputValueClass, NSError *__autoreleasing *error) { 
    // Validate the input and output 
    RKValueTransformerTestInputValueIsKindOfClass(inputValue, [NSString class], error); 
    RKValueTransformerTestOutputValueClassIsSubclassOfClass(outputValueClass, [State class], error); 

    State *state = [NSEntityDescription insertNewObjectForEntityForName:@"State" inManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext]; 

    state.abbreviation = inputValue; 

    *outputValue = state; 

    return YES; 
}]; 

回答

0

它看起來像你正在創建你的狀態對象,並將字符串設置爲對象的單個屬性。要做到這一點,你不需要一個自定義轉換器,你只需要使用一個零鍵路徑映射。

查看the Object-mapping wiki pageMapping Values without Key Paths部分。

相關問題