2012-08-29 149 views
5

如何爲NSManagedObject子類編寫自定義init?我想要例如initItemWithName:Volume:。其中Item是具有兩個屬性的NSManagedObject子類,namevolumeNSManagedObject子類的自定義初始化

+3

看看下面的問題http://stackoverflow.com/questions/10489578/custom-initializer-for-an-nsmanagedobject。可能我會幫你的。 –

+0

@NenadMihajlovic +1。好評! –

回答

6

卡洛斯,

由於內納德·米哈伊洛維奇建議你可以創建這個類別。例如,如果您有Item類,則可以創建一個名爲Item+Management的類別,並將創建代碼放在該類中。在這裏你可以找到一個簡單的例子。

// .h 

@interface Item (Management) 

+ (Item*)itemWithName:(NSString *)theName volume:(NSNumber*)theVolume inManagedObjectContext:(NSManagedObjectContext *)context; 

@end 

// .m 

+ (Item*)itemWithName:(NSString *)theName volume:(NSNumber*)theVolume inManagedObjectContext:(NSManagedObjectContext *)context 
{ 
    Item* item = (Item*)[NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:context]; 
    theItem.name = theName; 
    theItem.volume = theVolume; 

    return item; 
} 

當你想創建一個新的項目,不喜歡

#import "Item+Management.h" 

的進口和使用這樣

Item* item = [Item itemWithName:@"test" volume:[NSNumber numberWithInt:10] inManagedObjectContext:yourContext]; 
// do what you want with item... 

這種方式非常靈活,很容易在維護應用開發。

您可以在Stanford Course Lecture 14代碼示例中找到更多信息。另外,請參閱斯坦福大學的iTunes免費視頻(如果您有Apple ID)。

希望有所幫助。

P.S.爲了簡單起見,我想nameNSStringvolumeNSNumber。對於volume,最好使用NSDecimalNumber類型。

+0

非常感謝Flex_Addicted!但是,有一個問題:爲什麼我們要在類中創建這些方法,而不是在'NSManagedObject'子類中創建這些方法?我有幾門課,我至少需要7門課。 – Carlos

+0

您可以在http://stackoverflow.com/questions/9297101/nsmanagedobjects-with-categories和http://blog.chrismiles.info/2011/06/organising-core-data-for-ios.html上找到相關信息。 (我喜歡後者的很多技巧)。如果您使用Xcode爲您的託管對象生成自定義類,那麼這個簡單的解釋是:如果您修改實體中的某些內容,然後生成類以適應這些更改,Xcode將覆蓋您在原始子類中編寫的代碼。 –

+0

明白了!非常感謝!! – Carlos

相關問題