wuntee
wuntee

Reputation: 12470

iOS Obj-C. Posing correct solution?

I am at a place in my application where essentially every ViewController has a local NSManagedObjectContext:

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

and every segue passes the managedObjectContext via the same setter

[segue.destinationViewController setManagedObjectContext:self.managedObjectContext];

Coming from Java, it would be easy to create an abstract class that each ViewController implementes. In Objective-c it doesnt seem like that is possible. What I am looking to do is have a base class that performs this passing, but basically anything that implements UIViewController will have this (including just a plain UIViewController as well as a UITableViewController). Would it be possible/correct to have create an "abstract" class that poses as UIViewController that does this?

Update:

UIViewController+ManagedObjectContext.h

@interface UIViewController (ManagedObjectContext)
@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@end

UIViewController+ManagedObjectContext.m

#import "UIViewController+ManagedObjectContext.h"
@implementation UIViewController (ManagedObjectContext){
    NSManagedObjectContext *context;    // This is not valid, cant have local variables
}
@synthesize managedObjectContext; // This is not valid, must be @dynamic
-(void)setManagedObjectContext:(NSManagedObjectContext *)context{
    //How do you have a local NSManagedObjectContext?
}
@end

Upvotes: 9

Views: 1552

Answers (2)

railwayparade
railwayparade

Reputation: 5156

You can get the managedObjectContext from a managed object rather than pass it separately. Generally its more logical to pass the managed object.

For example: Say you have a managed object called thing, you can get the managedObjectContext by calling

NSManagedObjectContext *moc=[thing managedObjectContext];

Alternatively you can get the managed object context from the application delegate:

AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *moc = delegate.managedObjectContext;

Upvotes: 5

rob mayoff
rob mayoff

Reputation: 385500

You can just make your own subclass of UIViewController, let's say MOCViewController, with the managedObjectContext property. Then make all of your other view controllers be subclasses of MOCViewController instead of directly subclassing UIViewController.

If you really want to do it with a category, your category can use objc_setAssociatedObject to attach the managed object context to the view controller.

If you only really have one managed object context and you're just passing it around everywhere, consider just putting the context in a property of your application delegate, or in a global variable.

Upvotes: 5

Related Questions