1

我一直在尝试将 Core Data 合并到以标准视图控制器开头的情节提要应用程序中,但我正在遵循的教程使用标签栏作为初始视图。

有没有办法使用初始视图控制器启动应用程序,然后在应用程序委托中应用标签栏?本教程使用应用程序委托来实现核心数据,并使用标签栏控制器作为初始视图。

这是应用程序delegate.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;

@end

这是应用程序 delegate.m 文件

#import "AppDelegate.h"

#import "PersonsTVC.h"
#import "RolesTVC.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
@synthesize fetchedResultsController = __fetchedResultsController;

- (void)insertRoleWithRoleName:(NSString *)roleName
{
Role *role = [NSEntityDescription insertNewObjectForEntityForName:@"Role"
                                               inManagedObjectContext:self.managedObjectContext];

role.name = roleName;

[self.managedObjectContext save:nil];
}

- (void)importCoreDataDefaultRoles {

NSLog(@"Importing Core Data Default Values for Roles...");
[self insertRoleWithRoleName:@"C/C++ Developer"];
[self insertRoleWithRoleName:@"Obj-C Developer"];
[self insertRoleWithRoleName:@"Java Developer"];
[self insertRoleWithRoleName:@"ASP.NET Developer"];
[self insertRoleWithRoleName:@"Unix Engineer"];
[self insertRoleWithRoleName:@"Windows Engineer"];
[self insertRoleWithRoleName:@"Business Analyst"];
[self insertRoleWithRoleName:@"Infrastructure Manager"];
[self insertRoleWithRoleName:@"Project Manager"];
[self insertRoleWithRoleName:@"Operations Manager"];
[self insertRoleWithRoleName:@"Desktop Support Analyst"];
[self insertRoleWithRoleName:@"Chief Information Officer"];
NSLog(@"Importing Core Data Default Values for Roles Completed!");
}
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"Role"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);

// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];

// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"Person.name = Blah"];

// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name"
                                                                                 ascending:YES
                                                                                  selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                    managedObjectContext:self.managedObjectContext
                                                                      sectionNameKeyPath:nil
                                                                               cacheName:nil];
[self.fetchedResultsController performFetch:nil];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupFetchedResultsController];

if (![[self.fetchedResultsController fetchedObjects] count] > 0 ) {
    NSLog(@"!!!!! ~~> There's nothing in the database so defaults will be inserted");
    [self importCoreDataDefaultRoles];
}
else {
    NSLog(@"There's stuff in the database so skipping the import of default data");    
}

// The Tab Bar
UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

// The Two Navigation Controllers attached to the Tab Bar (At Tab Bar Indexes 0 and 1)
UINavigationController *personsTVCnav = [[tabBarController viewControllers] objectAtIndex:0];
UINavigationController *rolesTVCnav = [[tabBarController viewControllers] objectAtIndex:1];

// The Persons Table View Controller (First Nav Controller Index 0)
PersonsTVC *personsTVC = [[personsTVCnav viewControllers] objectAtIndex:0];
personsTVC.managedObjectContext = self.managedObjectContext;    

// The Roles Table View Controller (Second Nav Controller Index 0)
RolesTVC *rolesTVC = [[rolesTVCnav viewControllers] objectAtIndex:0];
rolesTVC.managedObjectContext = self.managedObjectContext;

//NOTE: Be very careful to change these indexes if you change the tab order

// Override point for customization after application launch.
// UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
// RolesTVC *controller = (RolesTVC *)navigationController.topViewController;
// controller.managedObjectContext = self.managedObjectContext;
return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
/*
 Sent when the application is about to move from active to inactive state. This can occur     for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
 Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
 */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
/*
 Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
 If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
 */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
/*
 Called as part of the transition from the background to the inactive state; here you can   undo many of the changes made on entering the background.
 */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
/*
 Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
 */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}

- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
    if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    } 
}
}

#pragma mark - Core Data stack

/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store
coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext
{
if (__managedObjectContext != nil)
{
    return __managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
    __managedObjectContext = [[NSManagedObjectContext alloc] init];
    [__managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return __managedObjectContext;
}

/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created from the application's model.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (__managedObjectModel != nil)
{
    return __managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
__managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return __managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
    return __persistentStoreCoordinator;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"StaffManager.sqlite"];

NSError *error = nil;
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];


NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                         [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
{
    /*
     Replace this implementation with code to handle the error appropriately.

     abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 

     Typical reasons for an error here include:
     * The persistent store is not accessible;
     * The schema for the persistent store is incompatible with current managed object model.
     Check the error message to determine what the actual problem was.


     If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.

     If you encounter schema incompatibility errors during development, you can reduce their frequency by:
     * Simply deleting the existing store:
     [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

     * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
     [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

     Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.

     */
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}    

return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory


- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

@end

如您所见,我正在尝试将核心数据添加到我的故事板应用程序中。在应用程序委托的这种情况下,我将标签栏控制器添加为根视图控制器,然后将控制器添加到标签栏。

我喜欢在应用程序委托的标签栏之前添加一个开始视图,然后添加标签栏及其各自的控制器。

我试图将标签栏添加为子视图,但托管对象没有被调用并且应用程序崩溃。

如果更有经验的程序员可以提供一些帮助,我真的很感激。如果需要,我可以通过电子邮件发送项目或上传代码。我需要指导人员,并且非常感谢我得到的任何帮助。

4

1 回答 1

0

好吧,我终于想通了。我向该栏添加了一个子视图作为选项卡栏的子项,并将其设置为第一个视图并且它可以工作。

于 2012-10-14T13:59:11.327 回答