开发者

NSManagedObjectContext: From a UIViewController, how do you get the ManagedObjectContext in iOS?

How do you know what the proper ManagedObjectContext is? Because I'm not in the appDelegate (where I think the code is) and I keep getting crashes in my app - specifically, in the 'ViewDidLoad' for MyTabBarViewController and the 'sendPressed' method for SecondViewController.

Could you tell me how to find the context? Because alloc init'ing my own context didn't work. Am I suppose to send a message to the appDelegate? I thought adding the appDelegate header file or calling it was the wrong thing to do.

SecondViewController.m

#import "SecondViewController.h"

@implementation SecondViewController

- (IBAction) sendPressed:(UIButton *)sender
{
    for(UIViewController *controller in self.tabBarController开发者_StackOverflow社区.viewControllers)
    {
        if([controller isKindOfClass:[FirstViewController class]])
        {
            FirstViewController *fvc = (FirstViewController *)controller;
            [fvc realLabel];
        }
    }

    //add image to Core Data
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    Photo *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:context];
    photo.photo = imageData;

    self.tabBarController.selectedIndex = 2;//switch over to the third view to see if it worked
}
...
@end

MyTabBarViewController.m

#import "MyTabBarViewController.h"


@implementation MyTabBarViewController
@synthesize pageControl,scroller;

-(IBAction)clickPageControl:(id)sender
{
    int page=pageControl.currentPage;
    CGRect frame=scroller.frame;
    frame.origin.x = frame.size.width * page;
    frame.origin.y = 0;
    [scroller scrollRectToVisible:frame animated:YES];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int page = scrollView.contentOffset.x/scrollView.frame.size.width;
    pageControl.currentPage=page;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    scroller.delegate=self;
    scroller.pagingEnabled=YES;
    scroller.directionalLockEnabled=YES;
    scroller.showsHorizontalScrollIndicator=NO;
    scroller.showsVerticalScrollIndicator=NO;
    scroller.contentSize=CGSizeMake(pageControl.numberOfPages*scroller.frame.size.width, scroller.frame.size.height);
    CGFloat scrollWidth = 0;
    int pageNumber = 0;
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Photo" inManagedObjectContext:context];
    NSError *error = nil;
    NSArray *fetchCount = [context executeFetchRequest:request error:&error];
    int pageCount = [fetchCount count];
    for (int i=0; i<pageCount; i++)
    {
        PhotoViewController *pvc = [[PhotoViewController alloc] initWithNibName:@"PhotoViewController" bundle:nil];
        CGRect rect = scroller.frame;
        rect.size.height = scroller.frame.size.height;
        rect.size.width = scroller.frame.size.width;
        rect.origin.x = scroller.frame.origin.x + scrollWidth;
        rect.origin.y = scroller.frame.origin.y;
        pvc.view.frame  = rect;
        [pvc view];
        pvc.label.text = [NSString stringWithFormat:@"%d", pageNumber];
        pvc.label.textColor = [UIColor redColor];
        Photo *photo = [[Photo alloc] init];
        photo = [fetchCount objectAtIndex:i];
        UIImage *fetchedImage = [UIImage imageWithData:photo.photo];
        pvc.imageView.image = fetchedImage;
        [scroller addSubview:pvc.view];
        [pvc release];
        pageNumber++;
        scrollWidth += scroller.frame.size.width;
    }
    pageControl.numberOfPages=pageCount;
    pageControl.currentPage=0;
    [self.view addSubview:scroller];
}

...

@end

If I import my CoreDataProjAppDelegate to each of these files and use NSManagedObjectContext *context = [(CoreDataProjAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; then it works fine. But is this the correct way?


You have to set the PersistentStoreCoordinator in order for the context to be valid:

NSPersistentStoreCoordinator *psc = ((CoreDataProjAppDelegate *)[UIApplication sharedApplication].delegate).persistentStoreCoordinator;
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    [context setPersistentStoreCoordinator:psc];

This is assuming you have a property on the app delegate named persistentStoreCoordinator which the default core data project will have. The psc is basically the link between your context (scratch pad) and your actual persistent storage (physical database).


Did you create your project with the "Use Core Data" box ticked? If you did that you'll have a managedObjectContext automatically, which you then pass to whatever other classes need it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜