2010-11-09 39 views
1

我已經使用核心數據構建了我的應用程序,但我遇到了如何解決保存和加載問題。核心數據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

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

回答

2

還好吧,首先,試着去理解數據的方式的核心工作。我認爲你非常接近,但編程是關於真正瞭解正在發生的事情,而不是'知道'發生了什麼。 Getting started with Core Data"指南非常具有啓發性。現在你的代碼(我不知道你是確切的數據模型和周圍的代碼,所以我有點猜測在這裏)。我假設你有一個名爲'datePicker'的成員,它引用了你正在使用的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]; 
} 
+0

編輯的問題包括代碼,希望你能幫助我。 – 2010-11-16 17:01:02

0

那麼,如果你的數據庫中有一個文本輸入實體,就給它一個date類型的屬性並選擇「indexed」。

然後我會開始一個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"

+0

我有這個但它不起作用:http://b.imagehost。org/view/0307/Screen_shot_2010-11-09_at_19_43_57 – 2010-11-09 19:46:01

+0

那麼,請看看您的所有警告,並嘗試理解並糾正它們。就我而言,我錯過了「[set setPredicate:predicate]」;在我上面的例子中。確保你的AppDelegate具有managedObjectContext屬性,並且你實際上並沒有使用你獲取的數據,因爲如果你閱讀你最後一次警告,你不使用數組。 – Bersaelor 2010-11-09 20:57:02

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]); 
} 
} 
+0

這是一個很棒的小代碼片段,但是我的主要問題是如何做到這一點,並用日期保存。因此,當用戶在UIDatePicker中選擇該日期時,會顯示相同的文本。 – 2010-11-15 07:41:11

+0

@Josh:在textViewDidEndEditing中,將datePicker中的「timeStamp」屬性保存爲唯一格式,因爲時間戳保存在1970年的格式中。所以它也會算第二。所以每當你從NSFetchRequest獲取文本時,每次「datepicker.date」都有不同的時間戳。立即保存2條記錄,然後在文檔目錄數據庫中查看。 – 2010-11-15 08:39:17

+0

好吧,我有這個:http://b.imagehost.org/0865/Screen_shot_2010-11-15_at_10_10_08.png我在正確的路線?我有一個名爲'Notes'的實體和一個名爲'note'的實體的屬性。所以這應該在離開文本視圖時保存文本並在更改日期選擇器時加載,對嗎? – 2010-11-15 10:13:19