user1385666
user1385666

Reputation: 357

Creating a Core Data model object which isn't saved to the persistent store

I have an iOS application that uses core data. I've built my NSManagedObjectModel. I have an NEOrder entity there. I've generated NSManagedObject subclasses.

@interface NEOrder : NSManagedObject

@property //....

@end

I have a UIViewController's subclass. That needs to have and instance variable of type NEOrder. But I want it to behave like a common custom object:

@interface NEOrder : NSObject

@property //....

@end

Of course it can be done by creating another .h and .m file with declaration of NEOrder_ subclassing NSObject there. But this file will be very similar to core data generated NSObjectModels, except @synthesize/@dynamic and init method. I don't want to do the work twice. Help me please, how can it be done?

if I'm adding init to the generated NEOrder app gets crashed:

-(id)init
{
    if (self=[super init])
    {
        self.name=[[NSString alloc] init];
        self.phone=[[NSString alloc] init];
        self.weight=[[NSNumber alloc] init];
        self.fromDirection=[[NEDirection alloc] init];
        self.toDirection=[[NEDirection alloc] init];
    }
    return self;
}

And another few words about how I want to use it.

//NEOrder *order is an instance of view controller
self.order=[NEOrder alloc] init]
//...
self.order.name=@"order name";
self.order.phone=@"12344321";

Is it possible? Or I have to create a separate NSObject's subclass for that?

Upvotes: 1

Views: 534

Answers (3)

coder
coder

Reputation: 10520

Use a Category. Categories can be used to write methods for a class outside of the actual class. I use them with Core Data models so when I need to regenerate the NSManagedObjectModel for any reason, I keep the methods.

Upvotes: 1

NikosM
NikosM

Reputation: 1131

All classes inherit from NSObject so NSManagedObject inherits from NSObject too. This means that your NEOrder objects will have all the characteristics of an NSObject.

Upvotes: 1

paulmelnikow
paulmelnikow

Reputation: 17208

One part of your question doesn't make sense:

I want it to behave like a common custom object.

What do you mean?

The rest of your question suggests you need a single NEOrder class, and that you should set up your view controller like this:

MyViewController.h:

@class NEOrder;

@interface MyViewController : UIViewController

@property (strong) NEOrder *order;

@end

MyViewController.m:

#include "NEOrder.h"

@implementation MyViewController

...

@end

Upvotes: 2

Related Questions