【问题标题】:Core Data iPhone - Save/Load depending on DateCore Data iPhone - 根据日期保存/加载
【发布时间】:2010-11-09 12:01:57
【问题描述】:

我已经使用核心数据构建了我的应用程序,但是我在如何进行保存和加载时遇到了麻烦。

我有一个 UIDatePicker。我有一个 UITextView。

我想保存用户在 UITextView 中键入的内容。然后,如果用户选择他们最初保存它的同一日期,我想将该文本加载回 UITextView。

像日历一样。

编辑

这是我的 appDelegate.h

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

@class coreDataViewController;

@interface OrganizerAppDelegate : NSObject <UIApplicationDelegate> {
    
    NSManagedObjectModel *managedObjectModel;
    NSManagedObjectContext *managedObjectContext;
    NSPersistentStoreCoordinator *persistentStoreCoordinator;
    
    coreDataViewController *viewController;
    
    UIWindow *window;
}

@property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel;
@property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet coreDataViewController *viewController;
- (NSString *)applicationDocumentsDirectory;
@end

appDelegate.m

#import "OrganizerAppDelegate.h"
#import "coreDataViewController.h"

@implementation OrganizerAppDelegate

@synthesize window;
@synthesize viewController;

@synthesize managedObjectModel;
@synthesize managedObjectContext;
@synthesize persistentStoreCoordinator;

#pragma mark -
#pragma mark Application lifecycle

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

    // Override point for customization after app launch
    [window addSubview:viewController.view];
    [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)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.
     */
}


/**
 applicationWillTerminate: saves changes in the application's managed object context before the application terminates.
 */
- (void)applicationWillTerminate:(UIApplication *)application {
    
    NSError *error = nil;
    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 -
#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;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Organizer" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];
    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 = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"Organizer.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 -
#pragma mark Application's Documents directory

/**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    
    [managedObjectContext release];
    [managedObjectModel release];
    [persistentStoreCoordinator release];
    
    [window release];
    [super dealloc];
}


@end

viewController.m(无论如何重要的一点,围绕它的所有代码都可以忽略,因为它无关紧要,与 UIDatePicker (datePicker) 或 UITextView (notesView) 无关。

-(void)textViewDidEndEditing:(UITextView *)textView { 
    NSManagedObjectContext *context = [OrganizerAppDelegate managedObjectContext]; 
    NSManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:context]; 
    [note setValue:notesView.text forKey:@"text"]; 
    [note valueForKey:@"text"];
    
    NSError *err=nil; if (![context save:&err]) { NSLog(@"Whoops, couldn't save: %@", [err localizedDescription]); } }

    NSDate *dtTemp = [pkrDate.date retain];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
    [dateFormatter setDateFormat:@"HH"]; 
    hour = [[dateFormatter stringFromDate:dtTemp]intValue]; 
    [dateFormatter setDateFormat:@"mm"]; 
    mins = [[dateFormatter stringFromDate:dtTemp]intValue]; 
    [dateFormatter setDateFormat:@"ss"]; 
    sec = [[dateFormatter stringFromDate:dtTemp]intValue]; 
    NSTimeInterval *timeInterval = [dtTemp timeIntervalSince1970]; 
    timeInterval = timeInterval - (hour*3600+mins*60+sec); 
    timeStamp = [[NSDate dateWithTimeIntervalSince1970:timeInterval]retain];

- (void) dateChanged:(id)sender{
    
    //Load...
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Text" inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity:entityDescription];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"(timeStamp = %@)",datePicker.date];
    [request setPredicate:predicate]; //added this line later
    NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    //check whether the array has entrys and do something with those objects here
    
    [monTable reloadData];
    [tueTable reloadData];
    [wedTable reloadData];
    [thuTable reloadData];
    [friTable reloadData];
}

【问题讨论】:

    标签: iphone objective-c core-data uitextview uidatepicker


    【解决方案1】:

    好的,首先,尝试了解核心数据的工作原理。我认为您已经很接近了,但是编程就是真正了解正在发生的事情,而不是“有点”知道正在发生的事情。 Getting started with Core Data" 指南很有启发性。

    现在关于您的代码(我不知道您是确切的数据模型和周围的代码,所以我在这里有点猜测)。我假设您有一个名为“datePicker”的成员,它指的是您正在使用的日期选择器。

    好的,让我看看我是否可以快速修复您的代码中的一些问题,但要小心一点。我没有通读你的源代码的每一行,也没有尝试编译它,所以可能仍然会有错误。到最后,你还是能对代码有一个透彻的理解。

    -  (void)textViewDidEndEditing:(UITextView *)textView { 
        NSManagedObjectContext *context = [OrganizerAppDelegate managedObjectContext]; 
        NSManagedObject *note = [NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:context]; 
        [note setValue:notesView.text forKey:@"text"]; 
    
        // Set the timestamp as well.
        [note setValue:datePicker.date forKey:@"timeStamp"];
    
        NSError *err=nil; if (![context save:&err]) { NSLog(@"Whoops, couldn't save: %@", [err localizedDescription]); } }
    
    /* Beware, we're just storing every edit here, without every throwing anything away. We'll try to display just the latest note in the 'dateChanged', but you might want to delete any previous notes first.*/
    
    /* I don't think this whole dissecting and generating a date is necessary */
    
    - (void) dateChanged:(id)sender{
    
        //Load...
        NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Text" inManagedObjectContext:self.managedObjectContext];
        NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
        [request setEntity:entityDescription];
    
        NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                  @"(timeStamp = %@)",datePicker.date];
        [request setPredicate:predicate]; //added this line later
        NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
    
        // Assuming that the last item in the array is the item that was added last. This might or might not be reasonable.
        notesView.text = [[array lastObject] text];
    
        [monTable reloadData];
        [tueTable reloadData];
        [wedTable reloadData];
        [thuTable reloadData];
        [friTable reloadData];
    }
    

    【讨论】:

      【解决方案2】:

      当您添加或编辑任何对象时,您应该将该对象保存在 MOC(ManagedObjectContect) 中。

      这里是修改后的代码:

      -(void)textViewDidEndEditing:(UITextView *)textView{
       NSManagedObjectContext *context=[YourAppDelegate managedObjectContext];
       NSManagedObject *note=[NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:context];
       [note setValue:notesView.text forKey:@"text"];
       [note valueForKey:@"text"] ;
      
       NSError *err=nil;
       if (![context save:&err]) {
        NSLog(@"Whoops, couldn't save: %@", [err localizedDescription]);
       }
      }
      

      【讨论】:

      • 这是一个很棒的小代码 sn-p,但我的主要问题是如何做到这一点,并用日期保存它。因此,当用户在 UIDatePicker 中选择该日期时,会显示相同的文本。
      • @Josh:在 textViewDidEndEditing 中,以唯一格式保存 datePicker 中的“timeStamp”属性,因为时间戳保存在 1970 年格式的参考中。所以它也算第二个。因此,每当您从 NSFetchRequest 获取文本时,每次“datepicker.date”都有不同的时间戳。立即保存2条记录,然后在文档目录数据库中查看。
      • 好的,我有这个:b.imagehost.org/0865/Screen_shot_2010-11-15_at_10_10_08.png 我在正确的路线上吗?我有一个名为“Notes”的实体和该实体的一个名为“note”的属性。所以这应该在离开文本视图时保存文本并在更改日期选择器时加载,对吧?
      • 同时存储“时间戳”。否则它将采用默认值。
      • NSDate *dtTemp=[pkrDate.date 保留]; NSDateFormatter *dateFormatter=[[[NSDateFormatter alloc] init] autorelease]; [dateFormatter setDateFormat:@"HH"];小时=[[dateFormatter stringFromDate:dtTemp]intValue]; [dateFormatter setDateFormat:@"mm"]; mins=[[dateFormatter stringFromDate:dtTemp]intValue]; [dateFormatter setDateFormat:@"ss"]; sec=[[dateFormatter stringFromDate:dtTemp]intValue]; NSTimeInterval timeInterval=[dtTemp timeIntervalSince1970]; timeInterval=timeInterval-(小时*3600+分钟*60+秒); timeStamp=[[NSDate dateWithTimeIntervalSince1970:timeInterval]retain];
      【解决方案3】:

      如果你的数据库中有一个文本条目实体,只需给它一个日期类型的属性并选择“索引”。

      然后我会像这样启动一个 NSFetchRequest:

      NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Text"
      inManagedObjectContext:self.managedObjectContext];
      NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
      [request setEntity:entityDescription];
      
      NSPredicate *predicate = [NSPredicate predicateWithFormat:
                                  @"(timeStamp = %@)",datepicker.date];
      [request setPredicate:predicate]; //added this line later
      NSArray *array = [self.managedObjectContext executeFetchRequest:request error:&error];
      //check whether the array has entrys and do something with those objects here
      

      当用户更改日期选择器的日期时。该数组将为空或保存您的文本条目。 虽然也许你应该先阅读"Developing with Core Data"

      【讨论】:

      • 好吧,请查看您的所有警告并尝试理解和纠正它们。就我而言,我错过了“[request setPredicate:predicate];”这一行。在我上面的例子中。确保您的 AppDelegate 具有 managedObjectContext 属性,并且您实际上并没有使用您获取的数据,因为如果您阅读最后一个警告,您就不会使用数组。
      猜你喜欢
      • 2010-11-16
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多