Skip to content

Commit

Permalink
Merge branch 'develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
helje5 committed Oct 10, 2023
2 parents 40e531d + 29e7ab2 commit 2955475
Show file tree
Hide file tree
Showing 10 changed files with 573 additions and 24 deletions.
5 changes: 5 additions & 0 deletions .spi.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
version: 1
builder:
configs:
- documentation_targets: [ ManagedModels ]

12 changes: 3 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,6 @@ ManagedModels has no other dependencies.
[`NSManagedObject`](https://developer.apple.com/documentation/coredata/nsmanagedobject)
(superclasses can't be added by macros),
e.g. `@Model class Person: NSManagedObject`.
- ToMany relationships must be a `Set<Target>`, a plain `[ Target ]` cannot be
used (yet?). E.g. `var contacts : Set<Contact>`.
- Properties cannot be initialized in the declaration,
e.g. this doesn't work: `var uuid = UUID()`.
Must be done in an initializers (requirement by `@NSManaged`).
- CoreData doesn't seem to support optional Swift base types like `Int?`.
- Uses the CoreData `@FetchRequest` property wrapper instead `@Query`.
- Doesn't use the new
[Observation](https://developer.apple.com/documentation/observation)
Expand All @@ -137,13 +131,10 @@ ManagedModels has no other dependencies.

#### TODO

- [x] Archiving/Unarchiving, required for migration.
- [ ] Figure out whether we can do ordered attributes: [Issue #1](https://github.com/Data-swift/ManagedModels/issues/1).
- [x] Figure out whether we can add support for array toMany properties: [Issue #2](https://github.com/Data-swift/ManagedModels/issues/2)
- [ ] Support for "autosave": [Issue #3](https://github.com/Data-swift/ManagedModels/issues/3)
- [ ] Support transformable types, not sure they work right yet: [Issue #4](https://github.com/Data-swift/ManagedModels/issues/4)
- [ ] Generate property initializers if the user didn't specify any inits: [Issue #5](https://github.com/Data-swift/ManagedModels/issues/5)
- [x] Generate `fetchRequest()` class function.
- [ ] Support SchemaMigrationPlan/MigrationStage: [Issue #6](https://github.com/Data-swift/ManagedModels/issues/6)
- [ ] Write more tests.
- [ ] Write DocC docs: [Issue #7](https://github.com/Data-swift/ManagedModels/issues/7), [Issue #8](https://github.com/Data-swift/ManagedModels/issues/8)
Expand All @@ -154,6 +145,9 @@ ManagedModels has no other dependencies.
- [ ] SwiftUI `@Query` property wrapper/macro?: [Issue 12](https://github.com/Data-swift/ManagedModels/issues/12)
- [ ] Figure out all the cloud sync options SwiftData has and whether CoreData
can do them: [Issue 13](https://github.com/Data-swift/ManagedModels/issues/13)
- [x] Archiving/Unarchiving, required for migration.
- [x] Figure out whether we can add support for array toMany properties: [Issue #2](https://github.com/Data-swift/ManagedModels/issues/2)
- [x] Generate `fetchRequest()` class function.
- [x] Figure out whether we can allow initialized properties
(`var title = "No Title"`): [Issue 14](https://github.com/Data-swift/ManagedModels/issues/14)

Expand Down
150 changes: 150 additions & 0 deletions Sources/ManagedModels/Documentation.docc/DifferencesToSwiftData.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# Differences to SwiftData

ManagedObjects tries to provide an API that is very close to SwiftData,
but it is not exactly the same API.

## Differences

The key difference when converting SwiftData projects:
- Import `ManagedModels` instead of `SwiftData`.
- Let the models inherit from the CoreData
[`NSManagedObject`](https://developer.apple.com/documentation/coredata/nsmanagedobject).
- Use the CoreData
[`@FetchRequest`](https://developer.apple.com/documentation/swiftui/fetchrequest)
instead of SwiftData's
[`@Query`](https://developer.apple.com/documentation/swiftdata/query).


### Explicit Superclass

ManagedModels classes must explicitly inherit from the CoreData
[`NSManagedObject`](https://developer.apple.com/documentation/coredata/nsmanagedobject).
Instead of just this in SwiftData:
```swift
@Model class Contact {}
```
the superclass has to be specified w/ ManagedModels:
```swift
@Model class Contact: NSManagedObject {}
```

> That is due to a limitation of
> [Swift Macros](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/macros/).
> A macro can add protocol conformances, but it cannot add a superclass to a
> type.

### CoreData @FetchRequest instead of SwiftData @Query

Instead of using the new SwiftUI
[`@Query`](https://developer.apple.com/documentation/swiftdata/query)
wrapper, the already available
[`@FetchRequest`](https://developer.apple.com/documentation/swiftui/fetchrequest)
property wrapper is used.

SwiftData:
```swift
@Query var contacts : [ Contact ]
```
ManagedModels:
```swift
@FetchRequest var contacts: FetchedResults<Contact>
```

### Properties

The properties work quite similar.

Like SwiftData, ManagedModels provides implementations of the
[`@Attribute`](https://developer.apple.com/documentation/swiftdata/attribute(_:originalname:hashmodifier:)),
`@Relationship` and
[`@Transient`](https://developer.apple.com/documentation/swiftdata/transient())
macros.

#### Compound Properties
More complex Swift types are always stored as JSON by ManagedModels, e.g.
```swift
@Model class Person: NSManagedObject {

struct Address: Codable {
var street : String?
var city : String?
}

var privateAddress : Address
var businessAddress : Address
}
```

SwiftData decomposes those structures in the database.


#### RawRepresentable Properties

Those end up working the same like in SwiftData, but are implemented
differently.
If a type is RawRepresentable by a CoreData base type (like `Int` or `String`),
they get mapped to the same base type in the model.

Example:
```swift
enum Color: String {
case red, green, blue
}

enum Priority: Int {
case high = 5, medium = 3, low = 1
}
```


### Initializers

A CoreData object has to be initialized through some
[very specific initializer](https://developer.apple.com/documentation/coredata/nsmanagedobject/1506357-init),
while a SwiftData model class _must have_ an explicit `init`,
but is otherwise pretty regular.

The ManagedModels `@Model` macro generates a set of helper inits to deal with
that.
But the general recommendation is to use a `convenience init` like so:
```swift
convenience init(title: String, age: Int = 50) {
self.init()
title = title
age = age
}
```
If the own init prefilles _all_ properties (i.e. can be called w/o arguments),
the default `init` helper is not generated anymore, another one has to be used:
```swift
convenience init(title: String = "", age: Int = 50) {
self.init(context: nil)
title = title
age = age
}
```
The same `init(context:)` can be used to insert into a specific context.
Often necessary when setting up relationships (to make sure that they
live in the same
[`NSManagedObjectContext`](https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext)).


### Migration

Regular CoreData migration mechanisms have to be used.
SwiftData specific migration APIs might be
[added later](https://github.com/Data-swift/ManagedModels/issues/6).


## Implementation Differences

SwiftData completely wraps CoreData and doesn't expose the CoreData APIs.

SwiftData relies on the
[Observation](https://developer.apple.com/documentation/observation)
framework (which requires iOS 17+).
ManagedModels uses CoreData, which makes models conform to
[ObservableObject](https://developer.apple.com/documentation/combine/observableobject)
to integrate w/ SwiftUI.
69 changes: 69 additions & 0 deletions Sources/ManagedModels/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# ``ManagedModels``

SwiftData like declarative schemas for CoreData.

@Metadata {
@DisplayName("ManagedModels for CoreData")
}

## Overview

[ManagedModels](https://github.com/Data-swift/ManagedModels/) is a package
that provides a
[Swift 5.9](https://www.swift.org/blog/swift-5.9-released/)
macro similar to the SwiftData
[@Model](https://developer.apple.com/documentation/SwiftData/Model()).
It can generate CoreData
[ManagedObjectModel](https://developer.apple.com/library/archive/documentation/DataManagement/Devpedia-CoreData/managedObjectModel.html)'s
declaratively from Swift classes,
w/o having to use the Xcode "CoreData Modeler".

Unlike SwiftData it doesn't require iOS 17+ and works directly w/
[CoreData](https://developer.apple.com/documentation/coredata).
It is **not** a direct API replacement, but a look-a-like.
Example model class:
```swift
@Model
class ToDo: NSManagedObject {
var title: String
var isDone: Bool
var attachments: [ Attachment ]
}
```
Setting up a store in SwiftUI:
```swift
ContentView()
.modelContainer(for: ToDo.self)
```
Performing a query:
```swift
struct ToDoListView: View {
@FetchRequest(sort: \.isDone)
private var toDos: FetchedResults<ToDo>

var body: some View {
ForEach(toDos) { todo in
Text("\(todo.title)")
.foregroundColor(todo.isDone ? .green : .red)
}
}
}
```

- Swift package: [https://github.com/Data-swift/ManagedModels.git](https://github.com/Data-swift/ManagedModels/)
- Example ToDo list app: [https://github.com/Data-swift/ManagedToDosApp.git](https://github.com/Data-swift/ManagedToDosApp/)



## Topics

### Getting Started

- <doc:GettingStarted>
- <doc:DifferencesToSwiftData>

### Support

- <doc:FAQ>
- <doc:Links>
- <doc:Who>
77 changes: 77 additions & 0 deletions Sources/ManagedModels/Documentation.docc/FAQ.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Frequently Asked Questions

A collection of questions and possible answers.

## Overview

Any question we should add: [info@zeezide.de](mailto:info@zeezide.de),
file a GitHub [Issue](https://github.com/Data-swift/ManagedModels/issues).
or submit a GitHub PR w/ the answer. Thank you!

## General

### Is the API the same like in SwiftData?

The API is very similar, but there are some significant differences:
<doc:DifferencesToSwiftData>.

### Is ManagedObjects a replacement for SwiftData?

It is not exactly the same but can be used as one, yes.
ManagedObjects allows deployment on earlier versions than iOS 17 or macOS 14
while still providing many of the SwiftData benefits.

It might be a sensible migration path towards using SwiftData directly in the
future.

### Which deployment versions does ManagedObjects support?

While it might be possible to backport further, ManagedObjects currently
supports:
- iOS 13+
- macOS 11+
- tvOS 13+
- watchOS 6+

### Does this require SwiftUI or can I use it in UIKit as well?

ManagedObjects works with both, SwiftUI and UIKit.

In a UIKit environment the ``ModelContainer`` (aka ``NSPersistentContainer``)
needs to be setup manually, e.g. in the `ApplicationDelegate`.

Example:
```swift
import ManagedModels

let schema = Schema([ Item.self ])
let container = try ModelContainer(for: schema, configurations: [])
```

### Are the `ModelContainer`, `Schema` classes subclasses of CoreData classes?

No, most of the SwiftData-like types provided by ManagedObjects are just
"typealiases" to the corresponding CoreData types, e.g.:
- ``ModelContainer`` == ``NSPersistentContainer``
- ``ModelContext`` == ``NSManagedObjectContext``
- ``Schema`` == ``NSManagedObjectModel``
- `Schema/Entity` == ``NSEntityDescription``

And so on. The CoreData type names can be used instead, but make a future
migration to SwiftData harder.

### Is it possible to use ManagedModels in SwiftUI Previews?

Yes! Attach an in-memory store to the preview-View, like so:
```swift
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
```

### Something isn't working right, how do I file a Radar?

Please file a GitHub
[Issue](https://github.com/Data-swift/ManagedModels/issues).
Thank you very much.
Loading

0 comments on commit 2955475

Please sign in to comment.