{"id":5803,"library":"pyobjc-framework-coredata","title":"PyObjC CoreData Framework","description":"PyObjC-framework-CoreData provides Python wrappers for Apple's Core Data framework on macOS. Core Data is a powerful framework that offers generalized and automated solutions for object life-cycle management, object graph persistence, and change tracking. This package, currently at version 12.1, is part of the broader PyObjC project, which typically sees minor releases every few months and major version updates roughly annually to align with macOS SDK changes.","status":"active","version":"12.1","language":"en","source_language":"en","source_url":"https://github.com/ronaldoussoren/pyobjc","tags":["macos","objective-c","cocoa","coredata","apple"],"install":[{"cmd":"pip install pyobjc-framework-coredata","lang":"bash","label":"Install pyobjc-framework-coredata"}],"dependencies":[{"reason":"Requires Python 3.10 or later.","package":"python","optional":false},{"reason":"Fundamental bridge library for all PyObjC framework bindings.","package":"pyobjc-core","optional":false}],"imports":[{"note":"Primary import for Core Data framework classes and functions.","symbol":"CoreData","correct":"import CoreData"},{"note":"Required for general PyObjC bridge functionality, decorators, and utilities.","symbol":"objc","correct":"import objc"}],"quickstart":{"code":"import CoreData\nimport objc\nimport os\n\n# 1. Define the Managed Object Model programmatically\nmodel = CoreData.NSManagedObjectModel.alloc().init()\nentity = CoreData.NSEntityDescription.alloc().init()\nentity.name = \"Event\"\nentity.managedObjectClassName = \"Event\"\n\nattribute_name = CoreData.NSAttributeDescription.alloc().init()\nattribute_name.name = \"name\"\nattribute_name.attributeType = CoreData.NSStringAttributeType\nattribute_name.optional = False\n\nattribute_timestamp = CoreData.NSAttributeDescription.alloc().init()\nattribute_timestamp.name = \"timestamp\"\nattribute_timestamp.attributeType = CoreData.NSDateAttributeType\nattribute_timestamp.optional = False\n\nentity.properties = [attribute_name, attribute_timestamp]\nmodel.entities = [entity]\n\n# 2. Create a Persistent Container\n# Use a unique in-memory store for a quick runnable example\ncontainer = CoreData.NSPersistentContainer.alloc().initWithName_managedObjectModel_(\n    \"MyCoreDataApp\", model\n)\n\n# Configure an in-memory store for the quickstart\nstore_description = CoreData.NSPersistentStoreDescription.alloc().init()\nstore_description.URL = None # For in-memory store\nstore_description.type = CoreData.NSInMemoryStoreType\ncontainer.persistentStoreDescriptions = [store_description]\n\ndef load_stores(completion_handler):\n    container.loadPersistentStoresWithCompletionHandler_(completion_handler)\n\n# Convert Python function to an Objective-C block using objc.block\n# This is necessary because loadPersistentStoresWithCompletionHandler_ expects an Objective-C block\n@objc.block\ndef store_load_handler(store_description, error):\n    if error:\n        print(f\"Failed to load persistent store: {error}\")\n    else:\n        print(f\"Successfully loaded store: {store_description.URL().path()}\")\n        # 3. Get the Managed Object Context\n        context = container.viewContext\n\n        # 4. Create and Save an NSManagedObject\n        Event = context.persistentStoreCoordinator().managedObjectModel().entitiesByName().get(\"Event\")\n        new_event = CoreData.NSManagedObject.alloc().initWithEntity_insertIntoManagedObjectContext_(\n            Event, context\n        )\n        new_event.setValue_forKey_(\"Python Demo Event\", \"name\")\n        new_event.setValue_forKey_(CoreData.NSDate.date(), \"timestamp\")\n        \n        # Save changes to the context (which saves to the store)\n        try:\n            context.save()\n            print(f\"Saved new event: {new_event.name()} at {new_event.timestamp()}\")\n        except Exception as e:\n            print(f\"Error saving context: {e}\")\n\n        # 5. Fetch NSManagedObjects\n        fetch_request = CoreData.NSFetchRequest.fetchRequestWithEntityName_(\"Event\")\n        events = context.executeFetchRequest_error_(fetch_request, objc.NULL)\n\n        if events:\n            print(\"Fetched Events:\")\n            for event_obj in events:\n                print(f\" - Name: {event_obj.name()}, Timestamp: {event_obj.timestamp()}\")\n        else:\n            print(\"No events found.\")\n\nload_stores(store_load_handler)\n\n# To keep the application running for asynchronous operations (if not in a GUI app)\n# For simple script, this might not be strictly needed as the completion handler finishes sync if in-memory.\n# In a real app, you'd use NSApplication.run() or similar.\n","lang":"python","description":"This quickstart demonstrates how to programmatically define a Core Data model, set up an `NSPersistentContainer` with an in-memory store, create, save, and fetch `NSManagedObject` instances using PyObjC. It highlights the use of `NSPersistentContainer` for simplified stack management and the Python-Objective-C bridge mechanics, particularly for asynchronous operations like loading persistent stores."},"warnings":[{"fix":"Ensure your project uses a Python version compatible with the installed PyObjC version (currently Python 3.10+ for v12.1). Refer to PyPI metadata for exact requirements.","message":"PyObjC has consistently dropped support for older Python versions with major releases. Python 3.9 was dropped in v12.0, and Python 3.8 was dropped in v11.0. Future major versions will likely continue this trend.","severity":"breaking","affected_versions":"11.0, 12.0+"},{"fix":"Review Apple's Core Data documentation for equivalent or alternative API usage. If applicable, migrate to newer Core Data APIs or adjust logic to avoid the removed constant.","message":"In CoreData, the constant `NSFetchRequestExpressionType` was removed as part of framework metadata updates in PyObjC 12.0.","severity":"breaking","affected_versions":"12.0+"},{"fix":"Code that directly interacts with Objective-C `init` methods at a low level, or relies on specific reference counting behavior before v11.1, may need review. Most high-level usage should be unaffected, but advanced use cases may require adjustment.","message":"The PyObjC bridge's handling of Objective-C initializer (`init` family) methods changed in v11.1 to correctly model ARC behavior, where `init` methods steal a reference to `self` and return a new one. This aligns with `clang`'s documentation.","severity":"gotcha","affected_versions":"11.1+"},{"fix":"If subclassing `NSManagedObject` in Python, be mindful of `__new__` and `__init__` interactions. For PyObjC-provided `__new__`, avoid overriding `__init__`. For user-implemented `__new__`, ensure `__init__` is correctly called, passing `self` and any arguments as needed.","message":"Subclassing `NSManagedObject` and overriding `__new__` requires careful handling of `__init__`. In PyObjC 10.3, support for calling `__init__` when `__new__` was provided by PyObjC was dropped, then partially reintroduced in 10.3.1 for user-implemented `__new__` methods. Code relying on the PyObjC-provided `__new__` still cannot use `__init__`.","severity":"gotcha","affected_versions":"10.3 - 10.3.x"},{"fix":"When developing multi-threaded applications with PyObjC and Core Data, strictly adhere to Core Data's concurrency guidelines: use a dedicated `NSManagedObjectContext` per thread, typically a main context for UI and private queue contexts for background operations, always using `performBlock` or `performBlockAndWait`.","message":"PyObjC 11.0 introduced experimental support for Python 3.13's free-threading (PEP 703). While an important step, `NSPersistentContainer` and Core Data contexts (`NSManagedObjectContext`) are generally not thread-safe. Each thread requiring data access should have its own `NSManagedObjectContext`.","severity":"gotcha","affected_versions":"11.0+"},{"fix":"Always call `context.save()` after creating, modifying, or deleting `NSManagedObject` instances to persist changes to the underlying store.","message":"In Core Data, you do not directly 'save' an `NSManagedObject`. Instead, changes made to objects within an `NSManagedObjectContext` are saved by calling the `save()` method on the context itself. Failing to save the context will result in unsaved changes, even if objects were created or modified.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}