我对这次派对有点迟到,但我为GroceryList做了类似的事情。我的数据存储在我需要在CoreData sqlite存储中的plist文件中。我编写了一个命令行基础工具,该工具在我的Mac上运行,分析plist文件,然后使用我的Core Data对象模型创建一个sqlite存储。我运行这个命令行工具作为我的构建的一部分(对于一些构建配置),以便我可以随意重新生成数据。要在xcode中创建这种工具,请选择文件 - >新建项目 - > Mac OS X - >命令行工具,然后从“类型”菜单中选择“核心数据”。下面是一些示例代码:
#import <objc/objc-auto.h>
int main (int argc, const char * argv[]) {
objc_startCollectorThread();
//You may not know this, but NSUserDefaults can be used to parse command line arguments!
//in this case, the arguments are passed in like this:
// -fullMomPath /hd/some/path/file.mom -fullStorePath /hd/some/path/file.sql
//by passing in the storePath, the calling script knows where the sqlite file will be and can copy it to the resulting application bundle
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
NSString *momPath = [args stringForKey:@"fullMomPath"];
NSString *storePath = [args stringForKey:@"fullStorePath"];
// Create the managed object context
NSManagedObjectContext *context = managedObjectContext(momPath, storePath);
//build and save your NSManagedObjects here
//in my case, i parse some plist files and create GroceryList type stuff, but whatever you do is your business.
return 0;
}
NSManagedObjectModel *managedObjectModel(NSString* momPath) {
static NSManagedObjectModel *model = nil;
if (model != nil) {
return model;
}
NSURL *modelURL = [NSURL fileURLWithPath:momPath];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return model;
}
NSManagedObjectContext *managedObjectContext(NSString* momPath, NSString* storePath) {
static NSManagedObjectContext *context = nil;
if (context != nil) {
return context;
}
context = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: managedObjectModel(momPath)];
[context setPersistentStoreCoordinator: coordinator];
NSString *STORE_TYPE = NSSQLiteStoreType;
NSURL *url = [NSURL fileURLWithPath:storePath];
NSError *error;
NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE configuration:nil URL:url options:nil error:&error];
if (newStore == nil) {
NSLog(@"Store Configuration Failure\n%@",
([error localizedDescription] != nil) ?
[error localizedDescription] : @"Unknown Error");
}
return context;
}
通过应用程序,你的意思是让Xcode生成模式?还是模式只能在运行时建立? – 2009-11-21 00:04:58
我不是100%确定。我想说它是在运行时生成的(我相信CoreData init的一部分是为了在需要时使数据存储保持最新状态),但是您需要仔细检查。 – 2009-11-21 00:38:21
Xcode不会生成模式。这是一个运行时操作。 – 2009-11-21 03:42:30