如何获取核心数据来保存/获取我的文件?

Posted

技术标签:

【中文标题】如何获取核心数据来保存/获取我的文件?【英文标题】:How Do I Get Core Data To Save /Fetch My Files? 【发布时间】:2011-03-31 05:26:49 【问题描述】:

我在这个主题上做了一些与错误等相关的主题,但他们都做了不同的事情,我无法让核心数据继续工作。我先解决一个问题,然后再解决另一个问题,等等。

应该发生什么:

用户在routineViewControler 中并单击导航栏中的+ 按钮。带有文本输入的 UIAlert 出现。用户输入文本,它应该成为表格中新单元格的标题,并使用 Core Data 保存。它应该保存在“常规”实体中的“名称”属性(字符串)中。

现在它没有保存或没有获取。

这是我的数据模型:

AppDelegate:

#import "CurlAppDelegate.h"
#import "ExcerciseNavController.h"
#import "RoutineTableViewController.h"

@implementation CurlAppDelegate


@synthesize window=_window;
@synthesize rootController;
@synthesize excerciseNavController;
@synthesize managedObjectContext=__managedObjectContext;

@synthesize managedObjectModel=__managedObjectModel;

@synthesize persistentStoreCoordinator=__persistentStoreCoordinator;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    // Override point for customization after application launch.
    [self.window addSubview:rootController.view];
    [self.window makeKeyAndVisible];
    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

    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */

- (void)dealloc

    [_window release];
    [rootController release];
    [excerciseNavController release];
    [__managedObjectContext release];
    [__managedObjectModel release];
    [__persistentStoreCoordinator release];
    [super dealloc];


- (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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
             */
            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:@"Curl" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];    
    return __managedObjectModel;



/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator

    if (__persistentStoreCoordinator != nil)
    
        return __persistentStoreCoordinator;
    

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

    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil 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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.

         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

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory

    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];



@end

RoutineViewController:

#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#import "Routine.h"
#import "CurlAppDelegate.h"

@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize managedObjectContext;

- (void)dealloc

    [managedObjectContext release];
    [eventsArray release];
    [super dealloc];


- (void)didReceiveMemoryWarning

    [super didReceiveMemoryWarning];


-(void)addEvent:(NSString *)name

    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

    NSManagedObject *newRoutineEntry;
    newRoutineEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

    NSError *error = nil;
    if (![context save:&error]) 
        // Handle the error.
    
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];




#pragma mark - View lifecycle

- (void)viewDidLoad

    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:context];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) 
        // Handle the error.
    
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];


-(void)toggleEdit

    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];


-(void)showPrompt

    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];


- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex

    if (buttonIndex != [alertView cancelButtonIndex])
    
        NSString *entered = [(AlertPrompt *)alertView enteredText];
        if(eventsArray && entered)
        
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        
    


- (void)viewDidUnload

    self.eventsArray = nil;
    [super viewDidUnload];


- (void)viewWillAppear:(BOOL)animated

    [super viewWillAppear:animated];


- (void)viewDidAppear:(BOOL)animated

    [super viewDidAppear:animated];


- (void)viewWillDisappear:(BOOL)animated

    [super viewWillDisappear:animated];


- (void)viewDidDisappear:(BOOL)animated

    [super viewDidDisappear:animated];


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

    return 1;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    return [eventsArray count];


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellEditingStyleDelete reuseIdentifier:CellIdentifier] autorelease];
   Routine* myRoutine = [self.eventsArray objectAtIndex:indexPath.row];
     cell.textLabel.text = name;
    return cell;

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath

    // Return NO if you do not want the specified item to be editable.
    return YES;


-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 

     if (editingStyle == UITableViewCellEditingStyleDelete) 

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) 
             // Handle the error.
         
     
 

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath


*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath

    // Return NO if you do not want the item to be re-orderable.
    return YES;

*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */


@end

【问题讨论】:

在 setEventsArray 之后的 viewDidLoad 中,您是否尝试过 [[self tableView] reloadData]; 【参考方案1】:

在您的addEvent: 方法中,您插入两个新的Routine 对象并保存它们,但是您永远不会对它们做任何其他事情。您没有设置它们的属性,也没有在完成后保存上下文。现在,您所做的只是用空白对象填充上下文。

您需要创建对象,更改它们的属性/属性值,然后才保存上下文。

【讨论】:

感谢@TechZen。所以我想我需要做一些事情来创建对象。所以我要保存的属性是“名称”,它是一个字符串。所以我分配并初始化一个字符串,也许做 string = [NSEntityDescription insertNewObjectForEntityForName:@"name" inManagedObjectContext:context];? 不,你没有从对象的角度思考。 “名称”是对象的属性。在这种情况下,您有一个 Routine 实体,它具有同名的 NSManagedObject 子类。所以,假设 Routine 有一个 name 属性,你可以在上面的代码中设置它,只用 routine.name=@"John Smith"; 感谢 techzen,我会试试这个,让你知道会发生什么。 我的 appDelegate 看起来还好吗?我是否弄乱了与 objectManagedContext 相关的代码?

以上是关于如何获取核心数据来保存/获取我的文件?的主要内容,如果未能解决你的问题,请参考以下文章

如何将获取的对象保存到核心数据

如何使用组合来分配从核心数据获取请求返回的元素数量?

核心数据保存和获取

如何仅使用月份和日期从核心数据中获取

如何在核心数据iOS中获取每个实体的最后一个条目

js如何获取缓存