2012-05-07 29 views
2

自定義初始化根據文檔:一個NSManagedObject

你不應該重寫初始化。你不鼓勵重寫initWithEntity:insertIntoManagedObjectContext:

而你應該改用awakeFromInsert或awakeFromFetch。

這很好,如果我只想設置一些屬性到當前日期或類似的,但如果我想發送另一個對象並根據其信息設置屬性呢?

例如,在一個名爲'Item'的NSManagedObject子類中,我想要一個initFromOtherThing:(Thing *)的東西,其中的項名被設置爲東西的名稱。我想避免'只需要記住'在創建項目後立即設置名稱,並且當我決定讓Item也基於Thing設置另一個默認屬性時,必須更新15個不同的控制器類。這些是與模型相關的行爲。

我該如何處理這個問題?

回答

1

我認爲處理這個問題的最好方法是繼承NSManagedObject,然後創建一個類別來保存要添加到對象中的內容。例如一對夫婦的類方法uniquing方便地創建:

+ (item *) findItemRelatedToOtherThing: (Thing *) existingThing inManagedObjectContext *) context { 
    item *foundItem = nil; 
    // Do NSFetchRequest to see if this item already exists... 
    return foundItem; 
} 

+ (item *) itemWithOtherThing: (Thing *) existingThing inContext: (NSManagedObjectContext *) context { 
    item *theItem; 
    if(!(theItem = [self findItemRelatedToOtherThing: existingThing inManagedObjectContext: context])) { 
     NSLog(@"Creating a new item for Thing %@", existingThing); 
     theItem = [NSEntityDescription insertNewObjectForEntityForName: @"item" inManagedObjectContext: context]; 
     theItem.whateverYouWant = existingThing.whateverItHas; 
    } 
    return theItem; 
} 

現在不調用過initWithEntity:insertIntoManagedObjectContext:直接只需使用您的方便類方法,如:

item *newItem = [item itemWithOtherThing: oldThing inContext: currentContext];