Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 756
wuntee Avatar asked Apr 18 '12 01:04

wuntee


2 Answers

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.

like image 198
rob mayoff Avatar answered Oct 20 '22 00:10

rob mayoff


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;
like image 37
railwayparade Avatar answered Oct 20 '22 00:10

railwayparade