2012-09-19 25 views
6

ガイがうまくいくことを望みます。アプリケーションを再起動するとデータが失われる(コアデータ)

私はiPhone開発には初めてです。私はコアデータを使用して簡単なアプリケーションを作成しています。私はデータを保存するアプリケーションの間、それは正常に動作し、私はデータを取得し、それもうまく動作します。しかし、アプリケーションを再起動すると、すべてのデータが失われます。

アプリケーションの起動時に、ViewDidLoad関数で、私が働いているアプリケーションで取得したのと同じ関数でデータを取得しています。

データの保存方法:

NSManagedObjectContext *context=[app managedObjectContext]; 
    Contacts *data=[NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context]; 
    if(nameField.text.length <=0 || phoneField.text.length <=0) 
    { 

     UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning!" message:@"Please enter some data." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil]; 
     [alert show]; 
    } 
    else 
    { 
     data.name = nameField.text; 
     data.phone = phoneField.text; 
     NSLog(data.name); 
     NSLog(data.phone); 
     [self.navigationController popToRootViewControllerAnimated:YES]; 

    } 

データの取得方法:

NSEntityDescription *entity=[NSEntityDescription entityForName:@"Database" inManagedObjectContext:context]; 

    NSFetchRequest *fetchRequest=[[NSFetchRequest alloc]init]; 

    [fetchRequest setFetchBatchSize:20]; 

    [fetchRequest setEntity:entity]; 

    NSSortDescriptor *sorting = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 

    NSArray *sorted_Array=[NSArray arrayWithObject:sorting]; 

    [fetchRequest setSortDescriptors:sorted_Array]; 

    NSError *error; 

    NSMutableArray *tArray=[[context executeFetchRequest:fetchRequest error:&error]mutableCopy]; 

    [self setArray:tArray]; 
    [self.tableView reloadData]; 

アプリの委任コード

#import "ZAppDelegate.h" 
#import "Contacts.h" 

@implementation ZAppDelegate 

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

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; 
    // Override point for customization after application launch. 

    TableViewController *TVC=[[TableViewController alloc]init]; 

    TVC.MOcontext=self.managedObjectContext; 

    UINavigationController *nvgc=[[UINavigationController alloc]initWithRootViewController:TVC]; 
    self.window.rootViewController=nvgc; 


    self.window.backgroundColor = [UIColor whiteColor]; 
    [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 
{ 
    // 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:@"Diary" 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:@"Diary.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. 

     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 

ここに何か間違っていますか? 私はできるだけ早く良い答えを得ることを望んでいます。

+1

あなたが投稿したコードでは、 'NSManagedObjectContext'という' save'メッセージを送信しません。そうするまで、あなたの変更は 'NSPersistentStore'に保存されません。 – FluffulousChimp

+0

@alanduncan:あなたのリプレイをありがとう。 NSPersistentStoreで私の変更をどのように維持できますか? – iOmi

+0

私はまったく同じことが起こっているが、VB.NETとDB = SQL Server 2012 Expressのコンソールアプリケーションを実行するVisual Studio 2012とEntityFrameworkを使用している。データは、.SaveChanges(各ループの最後に実行され、各ループが別の行を書き込む)を使用して保存されます。今、私がデバッグモードでアプリケーションをシャットダウンすると、データはまだそこにあります。問題ない。しかし、IDE経由でデバッグモードでアプリケーションを再起動すると、最後に実行したアプリケーションで実行されたすべてのデータ(最後に実行されたときに保存されたデータ)が削除され、そこから削除されます。私を狂わせるそれを解決できましたか?これを読んでいる人は誰でも助けてくれる? –

答えて

6

アプリケーションのライフサイクルによっては、NSManagedObjectContextsaveに電話する必要があります。変更しないと、NSPersistentStoreに保存されません。たとえば、アプリケーションデリゲートのapplicationDidEnterBackground:メソッドです。

NSError *saveError = nil; 
if(![[self managedObjectContext] save:&saveError]) { 
    // deal with error... 
} 

私はあなたのコード内に保存入れているところ私は

+0

@aladuncan ::私はアプリケーションのライフサイクル中にボタンアクションで** save **を呼び出しています。それは良くないのですか? – iOmi

+0

そして、このボタンアクションで 'NSManagedObject'コンテキストを保存したにもかかわらず、データが永続化されていませんか?通常は、アプリケーションがバックグラウンドに入ったときにもコンテキストを保存する必要があります。それ以外の場合は、ユーザーがホームボタンを押すとどうなりますか?その後、あなたのアプリは殺されますか? 'save'メソッドの結果をチェックして、エラーがないことを確認していますか? – FluffulousChimp

+0

@aladuncan ::はい! ** save **メソッドをチェックし、ブレークポイントを置いて、行ごとにデバッグしました。それはうまく動作します。私のアプリケーションが起動するたびに** Retreive **メソッドが呼び出されますが、何も出ません。データが保存されている(保持されている)か、データファイルに保存されていないかのデータを確認することができません。 私は、SQL Serverを使用してデータベースを作成するときに.NETと同様に、SQL Serverデータベースファイルを作成し、データの保存ではないことを確認できるファイルのサイズを計算すると仮定しています。 iOSでは、.NETのようなものはありませんか? – iOmi

0

が表示されていない...あなたのアプリケーションデリゲートが設定し、アップルのテンプレートが行うようにコアデータがスタックを維持することを想定しています。保存するには、managedcontextに指示する必要があります。あなたが行うことは、あなたのアプリとデザインによって異なります。既にあなたのアプリに入っていると思ったら、NSLogをいくつか追加してデバッグしたり、デバッガツールを使って実際にコードにステップインしてください。

これは簡単な修正です。がんばろう。あなたのAppDelegateで

+0

私は** NSLog **とデバッガツールを使用しました。アプリケーションは動作している間は正常に動作し、データを保存し、データを取得しますが、再起動するとすべてのデータが消滅します。 – iOmi

+1

NSPersistantストアの変更は、通常、アプリケーションdelegate.mにあります。そして、上記のように別の人がコンテキストを保存すると、app delegate.mファイルと一緒に保存されます。 app delegate.mファイル内のコードと、明示的に保存している場所を表示することをおすすめします。私は助けたいと思うが、私は両方の部分からコードを参照する必要があります。 NSLog..itを使って素晴らしい仕事をするのは、デバッグだけでなくデバッガを使う良い方法です。がんばり続ける! – holster

+0

::お返事ありがとうございます。遅くまでご返信いただきまして申し訳ありません。 ** appDelegate.m **コードで質問を更新しました。 ** appDelegate.m **の部分をご覧ください。 私が明示的に保存している部分は、Questionの上で既に述べた** Save Data Method **です。 – iOmi

4

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

-saveContextは、Xcodeのテンプレートの以前のバージョンで-saveかもしれません。


そして、もっと何、あなただけの他のクラスで-saveまたは-saveContentメソッドを呼び出すことができます。

[(AppDelegate *)[UIApplication sharedApplication] saveContext]; 
0

NSManagedObjectContextは、スクラッチパッドを提供します:あなたは、あなたのオブジェクトを好きなあなたが行うことができますが、最後にそれを保存する必要があります。 NSManagedObjectContextに行った変更は、保存するまで一時的です。あなたの方法の最後にこれを追加してみてください:

if (![context save:&error]) { 
NSLog(@"Couldn't save: %@", error); 
} 
0

このコンテキスト
CoreDataManagerを保存する必要が*コンテキスト= [CoreDataManager sharedInstance];
...
..
...
...
.....
...
[コンテキストsaveContext]。

関連する問題