Core Data iPhone - 根据日期保存/加载 [英] Core Data iPhone - Save/Load depending on Date

查看:129
本文介绍了Core Data iPhone - 根据日期保存/加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用核心数据构建了我的应用程序,但我遇到了如何解决保存和加载问题。



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



我想保存用户在UITextView中输入的内容。
然后,如果用户选择了他们最初保存日期的那个日期,那么我想将该文本加载到UITextView。



像日历一样。



希望你可以,我可以工作。



编辑:



这是我所做的,当然不工作。希望你能进一步帮助。
http://b.imagehost.org/view/0307/Screen_shot_2010 -11-09_at_19_43_57



编辑2:
好​​的,这是我的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

  #importOrganizerAppDelegate.h
#importcoreDataViewController.h

@implementation OrganizerAppDelegate

@合成窗口;
@synthesize viewController;

@synthesize managedObjectModel;
@synthesize managedObjectContext;
@synthesize persistStoreCoordinator;

#pragma mark -
#pragma mark应用程序生命周期

- (BOOL)应用程序:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//应用程序启动后覆盖自定义点
[window addSubview:viewController.view];
[window makeKeyAndVisible];

return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
/ *
当应用程序从活动移动到非活动状态。这可能发生在某些类型的临时中断(例如来电或SMS消息)时,或者当用户退出应用程序并且开始转换到后台状态时。
使用此方法暂停正在进行的任务,禁用计时器,并降低OpenGL ES帧速率。游戏应该使用这种方法暂停游戏。
* /
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
/ *
重新启动任何在应用程序处于非活动状态时暂停(或尚未启动)。如果应用程序先前在后台,则可选择刷新用户界面。
* /
}


/ **
applicationWillTerminate:在应用程序终止之前保存应用程序的受管对象上下文中的更改。
* /
- (void)applicationWillTerminate:(UIApplication *)application {

NSError * error = nil;
if(managedObjectContext!= nil){
if([managedObjectContext hasChanges]&&![managedObjectContext save:& error]){
/ *
用代码来正确处理错误。

abort()导致应用程序生成崩溃日志并终止。您不应在运送应用程序中使用此功能,但在开发过程中可能很有用。如果无法从错误中恢复,请显示一个警报面板,指示用户通过按主页按钮退出应用程序。
* /
NSLog(@未解析的错误%@,%@,错误,[错误userInfo]);
abort();
}
}
}


#pragma mark -
#pragma mark核心数据堆栈

/ **
返回应用程序的受管对象上下文。
如果上下文不存在,则将创建该上下文并将其绑定到应用程序的持久存储协调器。
* /
- (NSManagedObjectContext *)managedObjectContext {

if(managedObjectContext!= nil){
return managedObjectContext;
}

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


/ **
返回应用程序的管理对象模型。
如果模型不存在,则从应用程序的模型创建。
* /
- (NSManagedObjectModel *)managedObjectModel {

if(managedObjectModel!= nil){
return managedObjectModel;
}
NSString * modelPath = [[NSBundle mainBundle] pathForResource:@OrganizerofType:@momd];
NSURL * modelURL = [NSURL fileURLWithPath:modelPath];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return managedObjectModel;
}


/ **
返回应用程序的持久存储协调器。
如果协调器不存在,则会创建它并将应用程序的存储添加到其中。
* /
- (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]){
/ *
使用代码来替换此实现以适当地处理错误。

abort()导致应用程序生成崩溃日志并终止。您不应在运送应用程序中使用此功能,但在开发过程中可能很有用。如果无法从错误中恢复,请显示一个警报面板,指示用户通过按主页按钮退出应用程序。

此处的错误的典型原因包括:
*持久存储不可访问;
*持久存储的模式与当前管理对象模型不兼容。
检查错误消息以确定实际问题是什么。


如果永久存储不可访问,则文件路径通常有问题。通常,文件URL指向应用程序的资源目录,而不是可写目录。

如果在开发过程中遇到模式不兼容性错误,可以通过以下方式减少它们的频率:
*简单删除现有存储:
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil ]

*通过传递以下字典作为options参数执行自动轻量级迁移:
[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption,[NSNumber numberWithBool:YES],NSInferMappingModelAutomaticallyOption,零];

轻量级迁移只适用于一组有限的模式更改;有关详细信息,请参阅核心数据模型版本控制和数据迁移编程指南。

* /
NSLog(@未解析的错误%@,%@,错误,[错误userInfo]);
abort();
}

return persistentStoreCoordinator;
}


#pragma mark -
#pragma mark应用程序的文档目录

/ **
返回应用程序的Documents目录。
* /
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)lastObject];
}


#pragma mark -
#pragma mark内存管理

- (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:@ in b:












: nil; if(![context save:&err]){NSLog(@Whoops,could not 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 = [dtTemptimeIntervalSince1970];
timeInterval = timeInterval - (小时* 3600 +分钟* 60 +秒);
timeStamp = [[NSDate dateWithTimeIntervalSince1970:timeInterval] retain];

- (void)dateChanged:(id)sender {

// Load ...
NSEntityDescription * entityDescription = [NSEntityDescription entityForName:@TextinManagedObjectContext :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];
//检查数组是否有条目并在这里执行这些对象

[monTable reloadData];
[tueTable reloadData];
[wedTable reloadData];
[thuTable reloadData];
[friTable reloadData];
}


解决方案

尝试了解核心数据的工作原理。我认为你很接近,但编程是所有关于真正知道发生了什么,而不是kinda知道发生了什么。 Core Data入门指南相当具有启发性。 / p>

现在关于你的代码(我不知道你是精确的数据模型和周围的代码,所以我想在这里)。一个名为datePicker的成员,它引用您使用的日期选择器。



好吧,让我看看我是否可以快速修复代码中的一些问题,做一点小心,我没有读过你的源代码的每一行,我没有尝试编译它,所以可能仍然会有错误。最后,你仍然会彻底理解代码。

   - (void)textViewDidEndEditing:(UITextView *)textView {
NSManagedObjectContext * context = [OrganizerAppDelegate managedObjectContext];
NSManagedObject * note = [NSEntityDescription insertNewObjectForEntityForName:@NotesinManagedObjectContext:context];
[note setValue:notesView.text forKey:@text];

//也设置时间戳。
[note setValue:datePicker.date forKey:@timeStamp];

NSError * err = nil; if(![context save:& err]){NSLog(@Whoops,could not save:%@,[err localizedDescription]); }}

/ *请注意,我们只是在这里存储每一个编辑,而不是抛弃任何东西。我们将尝试只显示'dateChanged'中的最新注释,但你可能想要先删除任何先前的注释。* /

/ *我不认为这整个解剖和生成日期是必需的* /

- (void)dateChanged:(id)sender {

// Load ...
NSEntityDescription * entityDescription = [NSEntityDescription entityForName: @textinManagedObjectContext: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];

//假设数组中的最后一个项目是最后添加的项目。这可能是也可能不合理。
notesView.text = [[array lastObject] text];

[monTable reloadData];
[tueTable reloadData];
[wedTable reloadData];
[thuTable reloadData];
[friTable reloadData];
}


I have built my application using core data but I am having trouble how to work out saving and loading.

I have a UIDatePicker. I have a UITextView.

I want to save what the user types in the UITextView. Then I want to load that text back into the UITextView if the user selects the same date they originally saved it on.

Like a calendar.

Hope you can, I can work it out.

EDIT:

Here is what I have going, doesn't work of course. Hope you can help further. http://b.imagehost.org/view/0307/Screen_shot_2010-11-09_at_19_43_57

EDIT 2: Ok, here is my 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 (the bit that matters anyway, all the code around this can be ignored anyway as its irrelevant, no relation to the UIDatePicker (datePicker) or 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];
}

解决方案

Allright, first of all, try to understand how core data works. I think you're pretty close, but programming is all about really knowing what's going on, instead of 'kinda' knowing what's going on. The Getting started with Core Data" guide is quite instructive.

Now about your code (I don't know you're exact data-model and surrounding code, so I'm kinda guessing here). I'm assuming you have a member called 'datePicker', which refers to the datepicker that you're using.

Allright, let me see if I can quickly fix some things in your code, but do be a bit careful. I haven't read through every line of your source code, and I haven't tried compiling it, so there will probably still be errors. In the end, you'll still a thorough understanding of the code.

-  (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];
}

这篇关于Core Data iPhone - 根据日期保存/加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆