ios - NSManagedObjectContext:如何从 UIViewController 获取 iOS 中的 ManagedObjectContext?

标签 ios core-data uiviewcontroller nsmanagedobjectcontext

您如何知道正确的 ManagedObjectContext 是什么?因为我不在 appDelegate 中(我认为代码所在的位置)并且我的应用程序不断崩溃 - 特别是在 MyTabBarViewController 的“ViewDidLoad”和 SecondViewController 的“sendPressed”方法中。

你能告诉我如何找到上下文吗?因为分配初始化我自己的上下文不起作用。我应该向 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]; 然后它工作正常。但这是正确的方法吗?

最佳答案

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

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

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

关于ios - NSManagedObjectContext:如何从 UIViewController 获取 iOS 中的 ManagedObjectContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501319/

相关文章:

ios - UIModalTransitionStylePartialCurl 使我的应用程序崩溃

ios - Swift - 如何在核心数据中存储 MGLMapView 以在 TableView 上显示它?

iphone - 单元测试是否应该对主应用程序使用不同的托管对象上下文?

ios - 如何以编程方式弹出一个 View Controller 并呈现一个新的

iphone - 带分页的水平 UIScrollView

ios - View 堆栈、UIViewController 和旋转

ios - UILocalNotification 不发送

ios - 如何在 UITabBarController 和 UINavigationBarController 中呈现嵌入的 ViewController

ios - ios 10 的模拟器 .app 在 ios 8 中不起作用

iphone - 如何将核心数据添加到现有实用程序应用程序