0

見つけた中で最も単純なCoreDataの例を再現しようとしていますが、それでも問題が発生しました。SQLiteデータベースは私のエンティティに沿って作成されているようですが、実際のデータは追加されていません。これが私の.hファイルです:

#import <CoreData/CoreData.h>
#import "AppDelegate.h"

@interface MainViewController : UIViewController

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;

- (IBAction) createDatabase;

@end

そして、これが私の.mです。

#import "MainViewController.h"

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (IBAction) createDatabase
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _managedObjectContext = [appDelegate managedObjectContext];

    NSManagedObject *myMO = [NSEntityDescription insertNewObjectForEntityForName: @"Book" inManagedObjectContext: _managedObjectContext];

    [myMO setValue: [NSNumber numberWithInt: 123] forKey: @"bookID"];
    [myMO setValue: @"Example book." forKey: @"book"];
    [myMO setValue: @"Example author." forKey: @"author"];
    [myMO setValue: @"Example category." forKey: @"category"];
    [myMO setValue: [NSNumber numberWithBool: NO] forKey: @"isLiked"];
    [myMO setValue: [NSNumber numberWithBool: NO] forKey: @"isDisliked"];
}

@end

何が間違っているのか理解できません。Xcodeは、起動時にアプリのDocumentsディレクトリに.sqliteファイルを作成しますが、ボタンを押して呼び出すcreateDatabaseと、テキスト(「サンプルブック」)などがSQLiteファイルに入力されません。すべて。

私は何か間違ったことをしていますか?このコードはほとんどコピーアンドペーストされているので、何を間違えたのか本当にわかりません。

4

1 に答える 1

2

変更を保存するコードが見つかりません。それは次のようなものでなければなりません

 if (![myMO save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
 }

詳細については、このリンクを参照してください

  1. http://developer.apple.com/library/ios/#documentation/DataManagement/Conceptual/iPhoneCoreData01/Introduction/Introduction.html
  2. http://www.raywenderlich.com/934/core-data-on-ios-5-tutorial-getting-started
  3. https://blog.stackmob.com/2012/11/iphone-database-tutorial-part-1-learning-core-data/
于 2013-02-25T11:38:28.653 に答える