realm / realm-swift

Realm is a mobile database: a replacement for Core Data & SQLite
https://realm.io
Apache License 2.0
16.2k stars 2.14k forks source link

Use type-safe keyPath modify object #8521

Open Jaycyn opened 3 months ago

Jaycyn commented 3 months ago

How frequently does the bug occur?

Always

Description

Since type-safe keyPath syntax was added to Realm, I would expect that syntax to work everywhere, not just in queries. It does not appear to work with observe or updating/creating an object

A query pre 10.11.0. would be

let dogsSorted = dogs.sorted(byKeyPath: "name")

and the from 10.11.0. forward we can use

let dogsSorted = dogs.sorted(by: \.name)

That same syntax should work when updating objects (and everywhere else) as well.

Stacktrace & log output

No response

Can you reproduce the bug?

Always

Reproduction Steps

Supposed we have a Person object with the required primary key and a name string

class Person: Object {
    @Persisted(primaryKey: true) var _id: ObjectId
    @Persisted var name = ""
}

create an object and write it to Realm

let t0 = Person()
t0.name = "Jay"
try! realm.write {
   realm.add(t0)
}

then later, read that object in to update the name via the \.name keypath

let jay = realm.objects(Person.self).where { $0.name == "Jay" }.first!
print(jay)

outputs

Person {
    _id = 65f70df1a24efa5b3435f85b;
    name = Jay;
}

Now modify the name using type-safe keyPath

let modifiedJay = Person(value: [\Person._id: jay._id, \Person.name: "Modified Jay"])
print(modifiedJay)

and the output

Person {
    _id = 65f70df3a24efa5b3435f85e;
    name = ;
}

Note that neither the _id nor the name was property populated. However, using Strings as keys does work

let jay = realm.objects(Person.self).where { $0.name == "Jay" }.first!
print(jay)

let modifiedJay = Person(value: ["_id": jay._id, "name": "Modified Jay"])
print(modifiedJay)

outputs

Person {
    _id = 65f70df1a24efa5b3435f85b;
    name = Jay;
}
Person {
    _id = 65f70df1a24efa5b3435f85b;
    name = Modified Jay;
}

Note the primary key is the same and the name was updated.

Version

10.48.1

What Atlas Services are you using?

Local Database only

Are you using encryption?

No

Platform OS and version(s)

macOS Sonoma 14.2.1

Build environment

Xcode version: 15.3 Dependency manager and version: Realm 10.48.1

sync-by-unito[bot] commented 3 months ago

➤ PM Bot commented:

Jira ticket: RCOCOA-2311