我正在尝试重新创建我能找到的绝对最简单的核心数据示例,但我仍然设法遇到了问题。似乎 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 文件中全部。
难道我做错了什么?这段代码几乎是复制和粘贴的,所以我真的不知道我做错了什么。