0

我正在尝试重新创建我能找到的绝对最简单的核心数据示例,但我仍然设法遇到了问题。似乎 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 回答