Token导航 LogoToken导航

Agent Skill · 待分类

core-data(核心数据)

用于辅助数据整理、表格处理、CSV/Excel 分析、指标计算和图表准备。它适合让 Agent 清洗字段、汇总数据、发现异常、生成统计口径或把分析结果转成可读说明。使用时需要确认数据来源、字段含义和时间范围,避免把样本数据当全量事实;涉及敏感数据、导出文件或批量写回时,应先确认权限和脱敏边界。

core-data 是待分类类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在待分类类的 11,209 个 Skill 里排第 1,481。

总安装 3,084周安装 126GitHub Stars 528下载 988核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:core-data(核心数据)
来源仓库:https://github.com/dpearson2699/swift-ios-skills
仓库路径:skills/core-data
安装命令:
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-data
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-data

这个 Skill 是做什么的

这个 Skill 的分类还没最终确定,用法以来源仓库的说明为准。

管理 iOS 应用的 Core Data 持久化层,支持复杂数据模型与批量操作。适用于未采用 SwiftData 的项目,提供堆栈配置、并发控制与迁移策略。包含 NSFetchedResultsController 集成与测试用例编写指导。

安装方式:GitHub,命令为 npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-data。core-data 属于待分类类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/core-data

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-dat…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

core-data 怎么安装?

在终端执行 npx skills add https://github.com/dpearson2699/swift-ios-skills --skill core-data。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

core-data 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

core-data 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

core-data 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

core-data 用的人多吗?

公开数据是累计安装 3,084 次,近一周安装 126 次,下载 988 次,GitHub 528 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

core-data 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理待分类类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

待分类类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
infsh-cli

infsh CLI · Codex、Claude

4,374,576382权限未标注未明确未收录
ai-video-generation

AI 视频生成 · Codex、Claude

4,313,376382调用外部服务未明确有提醒
lark-openapi-explorer

云雀 OpenAPI 浏览器 · Codex、Claude

2,064,1209,011需要联网未明确有提醒
lark-workflow-standup-report

Lark 工作流程站立报告 · Codex、Claude

2,041,6328,978需要联网未明确通过
use-my-browser

使用我的浏览器 · Codex、Claude

1,848,49140操作浏览器未明确未通过
core-data

核心数据 · 本页

3,084528需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Core Data

Build and maintain data persistence using Core Data for apps that have not adopted SwiftData. Covers stack setup, concurrency, batch operations, NSFetchedResultsController, persistent history tracking, staged migration, and testing.

Contents

Stack Setup

NSPersistentContainer encapsulates the Core Data stack.

Docs: NSPersistentContainer

import CoreData

final class CoreDataStack: @unchecked Sendable {
    static let shared = CoreDataStack()

    let container: NSPersistentContainer

    private init() {
        container = NSPersistentContainer(name: "MyAppModel")
        container.loadPersistentStores { _, error in
            if let error { fatalError("Core Data store failed: \(error)") }
        }
        container.viewContext.automaticallyMergesChangesFromParent = true
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    }

    var viewContext: NSManagedObjectContext { container.viewContext }

    func newBackgroundContext() -> NSManagedObjectContext {
        container.newBackgroundContext()
    }
}

For CloudKit sync, use NSPersistentCloudKitContainer instead.

Concurrency and Threading

Core Data contexts are bound to queues. The viewContext is on the main queue; background contexts operate on private queues.

Docs: NSManagedObjectContext

Rules:

  • Always use perform(_:) or performAndWait(_:) when accessing a context off its own queue.
  • Never pass NSManagedObject instances across context or thread boundaries. Pass NSManagedObjectID instead and re-fetch.
  • Set automaticallyMergesChangesFromParent = true on the viewContext.
// Writing on a background context
func updateTrip(id: NSManagedObjectID, newName: String) async throws {
    let context = CoreDataStack.shared.newBackgroundContext()
    try await context.perform {
        guard let trip = try context.existingObject(with: id) as? CDTrip else {
            throw PersistenceError.notFound
        }
        trip.name = newName
        try context.save()
    }
}

Swift Concurrency Integration

NSManagedObjectContext.perform(_:) has an async throws overload (iOS 15+). Avoid marking NSManagedObject subclasses as Sendable.

func importItems(_ records: [ItemRecord]) async throws {
    let context = CoreDataStack.shared.newBackgroundContext()
    try await context.perform {
        for record in records {
            let item = CDItem(context: context)
            item.id = record.id
            item.title = record.title
        }
        try context.save()
    }
    // After save completes, viewContext auto-merges if configured
}

Do not use @unchecked Sendable on managed objects. If you need cross-boundary communication, pass the objectID (which is Sendable) and re-fetch:

let objectID = trip.objectID  // Sendable
Task.detached {
    let bgContext = CoreDataStack.shared.newBackgroundContext()
    try await bgContext.perform {
        let trip = try bgContext.existingObject(with: objectID) as! CDTrip
        trip.isFavorite = true
        try bgContext.save()
    }
}

NSFetchedResultsController

Efficiently drives UITableView / UICollectionView from a Core Data fetch request, with built-in change tracking and optional caching.

Docs: NSFetchedResultsController

import CoreData
import UIKit

class TripsViewController: UITableViewController, NSFetchedResultsControllerDelegate {

    private lazy var fetchedResultsController: NSFetchedResultsController<CDTrip> = {
        let request: NSFetchRequest<CDTrip> = CDTrip.fetchRequest()
        request.sortDescriptors = [
            NSSortDescriptor(keyPath: \CDTrip.startDate, ascending: false)
        ]
        request.fetchBatchSize = 20

        let controller = NSFetchedResultsController(
            fetchRequest: request,
            managedObjectContext: CoreDataStack.shared.viewContext,
            sectionNameKeyPath: nil,
            cacheName: "TripsCache"
        )
        controller.delegate = self
        return controller
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        try? fetchedResultsController.performFetch()
    }

    // MARK: - UITableViewDataSource

    override func numberOfSections(in tableView: UITableView) -> Int {
        fetchedResultsController.sections?.count ?? 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        fetchedResultsController.sections?[section].numberOfObjects ?? 0
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TripCell", for: indexPath)
        let trip = fetchedResultsController.object(at: indexPath)
        cell.textLabel?.text = trip.name
        return cell
    }

    // MARK: - NSFetchedResultsControllerDelegate (diffable)

    func controller(
        _ controller: NSFetchedResultsController<any NSFetchRequestResult>,
        didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference
    ) {
        let snapshot = snapshot as NSDiffableDataSourceSnapshot<String, NSManagedObjectID>
        dataSource.apply(snapshot, animatingDifferences: true)
    }
}

Key points:

  • The fetch request must have at least one sort descriptor.
  • Call deleteCache(withName:) before changing the fetch request predicate or sort descriptors, or set cacheName to nil.
  • The diffable snapshot delegate method (didChangeContentWith:) is available iOS 13+ and is preferred over the older per-change callbacks.
  • After a context reset(), call performFetch() again.

Batch Operations

Batch operations execute at the SQL level, bypassing the managed object context. They are fast but don't trigger context notifications automatically.

NSBatchInsertRequest (iOS 13+)

Docs: NSBatchInsertRequest

func batchImport(_ records: [[String: Any]]) async throws {
    let context = CoreDataStack.shared.newBackgroundContext()
    try await context.perform {
        let request = NSBatchInsertRequest(
            entity: CDTrip.entity(),
            objects: records
        )
        request.resultType = .objectIDs
        let result = try context.execute(request) as? NSBatchInsertResult
        if let ids = result?.result as? [NSManagedObjectID] {
            NSManagedObjectContext.mergeChanges(
                fromRemoteContextSave: [NSInsertedObjectsKey: ids],
                into: [CoreDataStack.shared.viewContext]
            )
        }
    }
}

NSBatchDeleteRequest (iOS 9+)

Docs: NSBatchDeleteRequest

func deleteOldTrips(before cutoff: Date) async throws {
    let context = CoreDataStack.shared.newBackgroundContext()
    try await context.perform {
        let fetchRequest: NSFetchRequest<NSFetchRequestResult> = CDTrip.fetchRequest()
        fetchRequest.predicate = NSPredicate(format: "endDate < %@", cutoff as NSDate)
        let request = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        request.resultType = .resultTypeObjectIDs
        let result = try context.execute(request) as? NSBatchDeleteResult
        if let ids = result?.result as? [NSManagedObjectID] {
            NSManagedObjectContext.mergeChanges(
                fromRemoteContextSave: [NSDeletedObjectsKey: ids],
                into: [CoreDataStack.shared.viewContext]
            )
        }
    }
}

NSBatchUpdateRequest (iOS 8+)

func markAllTripsAsNotFavorite() async throws {
    let context = CoreDataStack.shared.newBackgroundContext()
    try await context.perform {
        let request = NSBatchUpdateRequest(entity: CDTrip.entity())
        request.propertiesToUpdate = ["isFavorite": false]
        request.resultType = .updatedObjectIDsResultType
        let result = try context.execute(request) as? NSBatchUpdateResult
        if let ids = result?.result as? [NSManagedObjectID] {
            NSManagedObjectContext.mergeChanges(
                fromRemoteContextSave: [NSUpdatedObjectsKey: ids],
                into: [CoreDataStack.shared.viewContext]
            )
        }
    }
}

Always merge changes back into relevant contexts after batch operations. Batch delete does not enforce the Deny delete rule.

Persistent History Tracking

Track store-level changes across targets (app, extensions, widgets) and processes.

Docs: NSPersistentHistoryChangeRequest

Enable History Tracking

let description = NSPersistentStoreDescription()
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber,
    forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
container.persistentStoreDescriptions = [description]

Observe, Fetch, Merge, and Purge

// 1. Observe remote change notifications
NotificationCenter.default.addObserver(
    self, selector: #selector(storeRemoteChange(_:)),
    name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator
)

// 2. Fetch history since last token
@objc func storeRemoteChange(_ notification: Notification) {
    let context = container.newBackgroundContext()
    context.perform {
        let request = NSPersistentHistoryChangeRequest.fetchHistory(after: self.lastToken)
        if let result = try? context.execute(request) as? NSPersistentHistoryResult,
           let transactions = result.result as? [NSPersistentHistoryTransaction] {
            // 3. Merge into viewContext
            for transaction in transactions {
                self.container.viewContext.mergeChanges(fromContextDidSave: transaction.objectIDNotification())
                self.lastToken = transaction.token
            }
        }
        // 4. Purge old history
        let purgeRequest = NSPersistentHistoryChangeRequest.deleteHistory(before: self.lastToken)
        try? context.execute(purgeRequest)
    }
}

Store lastToken in UserDefaults (per target) so history is processed correctly across launches.

Staged Migration

NSStagedMigrationManager (iOS 17+) sequences schema migrations through ordered stages, each lightweight or custom.

Docs: NSStagedMigrationManager

import CoreData

// Define migration stages
// Use version checksums from the compiled model versions, not model names.
let checksumV1 = "<ModelV1 version checksum>"
let checksumV2 = "<ModelV2 version checksum>"
let stage1to2 = NSLightweightMigrationStage([checksumV1, checksumV2])
stage1to2.label = "Add isFavorite property"

let stage2to3 = NSCustomMigrationStage(
    migratingFrom: NSManagedObjectModelReference(
        named: "ModelV2", in: Bundle.main),
    to: NSManagedObjectModelReference(
        named: "ModelV3", in: Bundle.main)
)
stage2to3.label = "Split name into firstName/lastName"
stage2to3.willMigrateHandler = { migrationManager, currentStage in
    guard let container = migrationManager.container else { return }
    let context = container.newBackgroundContext()
    try context.performAndWait {
        // Transform data between schema versions
        let request = NSFetchRequest<NSManagedObject>(entityName: "Person")
        let people = try context.fetch(request)
        for person in people {
            let fullName = person.value(forKey: "name") as? String ?? ""
            let parts = fullName.split(separator: " ", maxSplits: 1)
            person.setValue(String(parts.first ?? ""), forKey: "firstName")
            person.setValue(parts.count > 1 ? String(parts.last!) : "", forKey: "lastName")
        }
        try context.save()
    }
}

// Apply to the persistent store
let manager = NSStagedMigrationManager([stage1to2, stage2to3])
let description = NSPersistentStoreDescription()
description.setOption(manager,
    forKey: NSPersistentStoreStagedMigrationManagerOptionKey)
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { _, error in
    if let error { fatalError("Migration failed: \(error)") }
}

For apps targeting below iOS 17, use lightweight migration (NSInferMappingModelAutomaticallyOption) or mapping models.

NSLightweightMigrationStage takes version checksums ([String]), not human-readable model names.

Composite Attributes

iOS 17+ supports composite attributes: groups of sub-attributes on an entity that act as a single logical unit. Define them in the model editor by adding a Composite type attribute and nesting sub-attributes beneath it.

Docs: NSCompositeAttributeDescription

Composite attributes map to Codable structs in SwiftData coexistence scenarios.

Testing

In-Memory Store for Tests

import CoreData
import Testing

struct CoreDataTests {
    func makeTestContainer() throws -> NSPersistentContainer {
        let container = NSPersistentContainer(name: "MyAppModel")
        let description = NSPersistentStoreDescription()
        description.type = NSInMemoryStoreType
        container.persistentStoreDescriptions = [description]

        var loadError: Error?
        container.loadPersistentStores { _, error in loadError = error }
        if let loadError { throw loadError }
        return container
    }

    @Test func createAndFetchTrip() throws {
        let container = try makeTestContainer()
        let context = container.viewContext

        let trip = CDTrip(context: context)
        trip.name = "Test Trip"
        trip.startDate = .now
        try context.save()

        let request: NSFetchRequest<CDTrip> = CDTrip.fetchRequest()
        let trips = try context.fetch(request)
        #expect(trips.count == 1)
        #expect(trips.first?.name == "Test Trip")
    }
}

Tips:

  • Share the NSManagedObjectModel instance across tests to avoid "duplicate entity" warnings.
  • Use a single shared model loaded once:
private let sharedModel: NSManagedObjectModel = {
    let url = Bundle.main.url(forResource: "MyAppModel", withExtension: "momd")!
    return NSManagedObjectModel(contentsOf: url)!
}()

func makeTestContainer() throws -> NSPersistentContainer {
    let container = NSPersistentContainer(name: "MyAppModel",
                                          managedObjectModel: sharedModel)
    // ... configure in-memory store
}

Common Mistakes

MistakeFix
Passing NSManagedObject across threadsPass objectID and re-fetch in the target context
Forgetting to merge batch operation resultsCall mergeChanges(fromRemoteContextSave:into:)
Calling save() without checking hasChangesGuard with context.hasChanges first
Using deprecated init(concurrencyType:) confinement typeUse .privateQueueConcurrencyType or .mainQueueConcurrencyType
Not setting mergePolicy on viewContextSet NSMergeByPropertyObjectTrumpMergePolicy to avoid conflict crashes
Modifying fetch request on live NSFetchedResultsController without deleting cacheCall deleteCache(withName:) first or use cacheName: nil
Batch delete ignoring Deny delete ruleBatch delete bypasses delete rules; validate manually
Marking NSManagedObject as @unchecked SendableDo not. Pass objectID instead

Review Checklist

  • NSPersistentContainer is initialized once and shared
  • viewContext used only on main queue; background contexts for writes
  • perform(_:) or performAndWait(_:) wraps all off-queue context access
  • automaticallyMergesChangesFromParent set on viewContext
  • mergePolicy set on viewContext to prevent conflict crashes
  • Batch operation results merged into relevant contexts
  • NSFetchedResultsController fetch requests have sort descriptors
  • Persistent history tracking enabled for multi-target apps
  • Tests use in-memory stores with shared NSManagedObjectModel
  • No NSManagedObject instances cross thread boundaries

References

平台分布

Codex

35.08%
按下载量换算347

Claude

28.25%
按下载量换算279

Cursor

20.68%
按下载量换算204

Gemini CLI

8.65%
按下载量换算85

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills