NSManagedObjectContext:从UIViewController,你如何获得iOS中的ManagedObjectContext?

时间:2011-06-28 03:46:33

标签: ios core-data uiviewcontroller nsmanagedobjectcontext

你怎么知道适当的ManagedObjectContext是什么?因为我不在appDelegate(我认为代码所在的地方)并且我在我的应用程序中不断崩溃 - 特别是在MyTabBarViewController的'ViewDidLoad'和SecondViewController的'sendPressed'方法中。

你能告诉我如何找到背景吗?因为alloc init'ing我自己的上下文不起作用。我想向appDelegate发送消息吗?我认为添加appDelegate头文件或调用它是错误的。

SecondViewController.m

#import "SecondViewController.h"

@implementation SecondViewController

- (IBAction) sendPressed:(UIButton *)sender
{
    for(UIViewController *controller in self.tabBarController.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

如果我将CoreDataProjAppDelegate导入到每个文件并使用NSManagedObjectContext *context = [(CoreDataProjAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];,那么它可以正常工作。但这是正确的方法吗?

2 个答案:

答案 0 :(得分:0)

您是否在勾选“使用核心数据”框的情况下创建了项目?如果你这样做了,你将自动拥有一个managedObjectContext,然后将其传递给其他需要它的类。

答案 1 :(得分:0)

您必须设置PersistentStoreCoordinator才能使上下文有效:

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

这假设您在名为persistentStoreCoordinator的app委托上有一个属性,默认核心数据项目将具有该属性。 psc基本上是您的上下文(便笺簿)与实际持久存储(物理数据库)之间的链接。