2012-08-29 145 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

相关问题