我正在制作一个基于核心数据的iPhone应用程序,它存储一些数据。
它有一个UITabBarController
作为根视图控制器(RootViewController
)。应用程序委托给选项卡控制器两个视图控制器-第一个是UIViewController
的实例,它代表应用程序的标题屏幕,第二个是用于显示数据的UITableViewController
。
这是我使用核心数据的第一个iPhone应用程序。我已经读过,构建这类应用程序的正确方法是在应用程序委托中创建和初始化managedObjectModel
、managedObjectContext
和persistentStoreCoordinator
对象,然后通过引用将managedObjectContext
传递给子视图控制器。我就是这么做的。
但是,我没有设法将managedObjectContext
对象传递给选项卡条控制器,我在应用程序委托的applicationDidFinishLaunching:
中初始化了该控制器
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions {
RootViewController *rootViewController = [[RootViewController alloc] init];
rootViewController.managedObjectContext = self.managedObjectContext;
[window addSubview:rootViewController.view];
[window makeKeyAndVisible];
[rootViewController release];
return YES;
}
即使选项卡条正确显示并加载标题屏幕视图控制器,它的managedObjectContext
仍然为零。我不知道我做错了什么。我还试图通过向RootViewController
添加一个新的保留属性来传递一个字符串。
我的RootViewController.h
如下所示:
@interface RootViewController : UITabBarController {
@private
NSManagedObjectContext *managedObjectContext;
}
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@end
我的RootViewController的viewDidLoad方法:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@", self.managedObjectContext);
ObiadViewController *obiadVC = [[ObiadViewController alloc] init];
ObiadListNavController *obiadListVC = [[ObiadListNavController alloc] init];
obiadVC.managedObjectContext = self.managedObjectContext;
obiadListVC.managedObjectContext = self.managedObjectContext;
NSArray *vcs = [NSArray arrayWithObjects:obiadVC, obiadListVC, nil];
self.viewControllers = vcs;
[obiadVC release];
[obiadListVC release];
}
我还检查了应用程序委托中的managedObjectContext
没有为零,就在它被传递给RootViewController
实例之前。这就像所有RootViewController
的ivars都会被重置一样。只有在这个时候才会发生。当我稍后从表视图控制器传递一个字符串到细节视图控制器时,一切都很好。
我希望我说得很清楚。我现在觉得自己很无知。
发布于 2011-04-23 05:26:24
UITabBarController类引用清楚地指出,不应该对UITabBarController进行子类化:
此类不是用于子类的。
在本例中,您可以实例化UITabBarController并在App的applicationDidFinishLaunching中向其添加视图控制器:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
tabBarController = [[UITabBarController alloc] init];
FirstViewController *firstViewController = [[FirstViewController alloc] init];
SecondViewController *secondViewController = [[SecondViewController alloc] init];
firstViewController.managedObjectContext = self.managedObjectContext;
secondViewController.managedObjectContext = self.managedObjectContext;
NSArray *vcs = [NSArray arrayWithObjects:firstViewController, secondViewController, nil];
tabBarController.viewControllers = vcs;
[window addSubview:tabBarController.view];
[window makeKeyAndVisible];
[firstViewController release];
[secondViewController release];
return YES;
}
希望能帮上忙。
https://stackoverflow.com/questions/5760243
复制