gpt4 book ai didi

xcode - 将 SQLite3 数据库逆向工程到 coredata

转载 作者:行者123 更新时间:2023-12-03 17:15:53 24 4
gpt4 key购买 nike

最初的问题是“我有一个 sqlite 3 db(字典),我想在新应用程序中使用它。是否有基于数据库结构创建核心数据关系模型的捷径?”

这就是我解决问题的方法 - 在网络上得到了很多帮助。

我简化了数据库,这使得编写核心数据模型变得非常容易。

我使用了来自此 great site 的 Python 脚本,来管理转换。

脚本如下:

import sqlite3;

inConn = sqlite3.connect('dictold.sqlite')
outConn = sqlite3.connect('dictnew.sqlite')

inCursor = inConn.cursor()
outCursor = outConn.cursor()

maxId = 0
inCursor.execute("select * from lexicon")
for row in inCursor:

if row[0] > maxId:
maxId = row[0]

# Create ZLEXICONENTITY entry
vals = []
vals.append(row[3]) # Z_PK
vals.append(1) # Z_OPT
vals.append(2) # Z_ENT
vals.append(row[0]) # ZIND
vals.append(row[1]) # ZENGLISH
vals.append(row[2]) # ZGREEK
outConn.execute("insert into ZLEXICONENTITY values(?, ?, ?, ?, ?, ?)", vals)


outConn.execute("update Z_PRIMARYKEY set Z_MAX=?", [maxId])

outConn.commit()

构建数据库后,我在将其连接到核心数据模型时遇到了问题。我收到一条消息“模型与数据库不匹配”。

解决方案是让 Core Data 从模型创建空数据库,然后让 Core Data 导入数据本身。

我首先将我的 sqlite 数据库(使用 Python 创建)导出到 sql,调用文件 db.sql(富有想象力!)。我只导出了数据表和主键表,没有导出元数据表。您也可以在命令行中执行此操作。我使用了一个名为 SQLiteManager 的应用程序。

除了处理持久存储 Controller 之外,核心数据中的所有代码都是库存代码。

代码如下:

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (persistentStoreCoordinator_ != nil) {
return persistentStoreCoordinator_;
}


NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"db.sql"];

// set up the backing store
NSFileManager *fileManager = [NSFileManager defaultManager];
// If the expected store doesn't exist, copy the default store.
if (![fileManager fileExistsAtPath:storePath]) {
NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"dict" ofType:@"sqlite"];
if (defaultStorePath) {
[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
}
}

NSURL *storeURL = [NSURL fileURLWithPath:storePath];

NSError *error = nil;
persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}

return persistentStoreCoordinator_;
}

很多人可能都知道这一切,但我不得不坚持几天。可能还有更简单的方法可以做到这一点。但也许它会帮助其他人..

最佳答案

没有。

Core Data 无法从现有架构推断出您的模型,您必须创建模型,然后自行迁移存储。

关于xcode - 将 SQLite3 数据库逆向工程到 coredata,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com