高级应用中CoreData的使用
发布时间: 2025-08-13 02:46:30 阅读量: 5 订阅数: 9 

### 高级应用中 Core Data 的使用
#### 1. 跨多个持久存储拆分数据
在很多应用里,数据存储是一个重要问题。通常,一个数据模型会关联一个持久存储,但有时将模型拆分为多个存储会更有优势。例如在 MyStash 应用中,所有的笔记和密码最初都存储在同一个持久存储 `MyStash.sqlite` 中。若要将笔记和密码分别存储在不同的持久存储中,可按以下步骤操作:
- **创建配置**:
1. 在 Xcode 中打开 `MyStash.xcdatamodel` 模型。
2. 选择默认配置(在实体列表下方),这里会显示与该配置关联的所有实体。初始时,只有默认配置,包含 `Note` 和 `System` 实体。
3. 点击并按住 Xcode 窗口底部的“Add Entity”按钮,从菜单中选择“Add Configuration”,添加一个名为 `Notes` 的配置。
4. 重复上述步骤,创建另一个名为 `Passwords` 的配置。
5. 将 `Note` 实体拖到 `Notes` 配置的实体列表中,将 `System` 实体拖到 `Passwords` 配置中。
- **创建持久存储**:打开 `AppDelegate.m`,修改 `persistentStoreCoordinator:` 方法,代码如下:
```objc
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (__persistentStoreCoordinator != nil)
{
return __persistentStoreCoordinator;
}
__persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
{
// Create the Notes persistent store
NSURL *noteStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Notes.sqlite"];
NSError *error = nil;
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:@"Notes" URL:noteStoreURL options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
{
// Create the Passwords persistent store
NSURL *passwordStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Passwords.sqlite"];
NSError *error = nil;
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:@"Passwords" URL:passwordStoreURL options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
return __persistentStoreCoordinator;
}
```
完成上述操作后,运行应用并添加新的笔记和密码条目进行验证。虽然应用界面可能没有明显变化,但这正是我们期望的,即底层持久存储结构的改变不应影响应用的其他部分。若要查看差异,可在终端中使用以下命令查找数据存储:
```bash
find ~/Library/Application\ Support/iPhone\ Simulator/ -name "*.sqlite"
```
打开 `Notes.sqlite` 数据库并运行 `.schema` 命令,会发现 `Note` 表有数据,而 `System` 表为空;打开 `Passwords.sqlite` 数据库,情况则相反。
#### 2. 添加加密
对于需要存储敏感信息的应用,数据加密至关重要。Core Data 本身对加密帮助不大,但也不会阻碍。数据加密有两种思路:加密整个数据库文件或仅加密数据存储中的选定字段。
- **使用数据保护进行持久存储加密**:iPhone 3GS 引入了硬件级磁盘加密,即数据保护。启用后,设备锁定时会加密部分磁盘,解锁时自动解密。
- **启用数据保护**:打开 iPhone 设置,导航到“Settings > General > Passcode Lock”,若未启用密码,先启用。若设置正确,页面底部会显示“Data protection is enabled”。
- **编程实现加密**:打开 `AppDelegate.m`,修改 `persistentStoreCoordinator:` 方法,添加文件属性以加密密码数据库,代码如下:
```objc
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
...
{
// Create the Passwords persistent store
NSURL *passwordStoreURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Passwords.sqlite"];
NSError *error = nil;
if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:@"Passwords" URL:passwordStoreURL options:nil error:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
// Encrypt the password database
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:NSFileProtectionComplete forKey:NSFileProtectionKey];
if (








