A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.mongodb.com/docs/atlas/device-sdks/sdk/swift/crud/update/ below:

CRUD - Update - Swift SDK - Atlas Device SDKs

Updates to Realm Objects must occur within write transactions. For more information about write transactions, see: Transactions.

The examples on this page use the following models:

@interface DogToy : RLMObject@property NSString *name;@end@interface Dog : RLMObject@property NSString *name;@property int age;@property NSString *color;@property DogToy *favoriteToy;@endRLM_COLLECTION_TYPE(Dog)@interface Person : RLMObject@property int _id;@property NSString *name;@property RLMArray<Dog *><Dog> *dogs;@property (readonly) RLMLinkingObjects *clubs;@endRLM_COLLECTION_TYPE(Person)@interface DogClub : RLMObject@property NSString *name;@property RLMArray<Person *><Person> *members;@end@implementation Dog@end@implementation DogToy@end@implementation Person+ (NSString *)primaryKey {    return @"_id";}+ (NSDictionary *)linkingObjectsProperties {    return @{        @"clubs": [RLMPropertyDescriptor descriptorWithClass:DogClub.class propertyName:@"members"],    };}@end@implementation DogClub@end
class Dog: Object {    @Persisted var name = ""    @Persisted var age = 0    @Persisted var color = ""    @Persisted var currentCity = ""    @Persisted var citiesVisited: MutableSet<String>    @Persisted var companion: AnyRealmValue        @Persisted var favoriteParksByCity: Map<String, String>}class Person: Object {    @Persisted(primaryKey: true) var id = 0    @Persisted var name = ""        @Persisted var dogs: List<Dog>            @Persisted var address: Address?}class Address: EmbeddedObject {    @Persisted var street: String?    @Persisted var city: String?    @Persisted var country: String?    @Persisted var postalCode: String?}

You can modify properties of a Realm object inside of a write transaction in the same way that you would update any other Swift or Objective-C object.

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock:^{        Dog *dog = [[Dog allObjectsInRealm: realm] firstObject];            dog.name = @"Wolfie";    dog.age += 1;}];
let realm = try! Realm()let dog = realm.objects(Dog.self).first!try! realm.write {            dog.name = "Wolfie"    dog.age += 1}
Tip Update Related and Embedded Objects

To update a property of an embedded object or a related object, modify the property with dot-notation or bracket-notation as if it were in a regular, nested object.

Object, Result, and List all conform to key-value coding . This can be useful when you need to determine which property to update at runtime.

Applying KVC to a collection is a great way to update objects in bulk. Avoid the overhead of iterating over a collection while creating accessors for every item.

let realm = try! Realm()let allDogs = realm.objects(Dog.self)try! realm.write {    allDogs.first?.setValue("Sparky", forKey: "name")        allDogs.setValue("Toronto", forKey: "currentCity")}

You can also add values for embedded objects or relationships this way. In this example, we add a collection to an object's list property:

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock:^() {        Person *ali = [[Person alloc] initWithValue:@{@"_id": @1, @"name": @"Ali"}];    [realm addObject:ali];        RLMResults<Dog *> *puppies = [Dog objectsInRealm:realm where:@"age < 2"];        [ali setValue:puppies forKey:@"dogs"];}];
let realm = try! Realm()try! realm.write {        let person = Person(value: ["id": 1, "name": "Ali"])    realm.add(person)    let dog = Dog(value: ["name": "Rex", "age": 1])    realm.add(dog)        let puppies = realm.objects(Dog.self).filter("age < 2")        person.setValue(puppies, forKey: "dogs")}

An upsert either inserts or updates an object depending on whether the object already exists. Upserts require the data model to have a primary key.

To upsert an object, call -[RLMRealm addOrUpdateObject:].

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock:^{    Person *jones = [[Person alloc] initWithValue:@{@"_id": @1234, @"name": @"Jones"}];            [realm addOrUpdateObject:jones];        Person *bowie = [[Person alloc] initWithValue:@{@"_id": @1234, @"name": @"Bowie"}];            [realm addOrUpdateObject:bowie];}];

To upsert an object, call Realm.add(_:update:) with the second parameter, update policy, set to .modified.

let realm = try! Realm()try! realm.write {    let person1 = Person(value: ["id": 1234, "name": "Jones"])            realm.add(person1, update: .modified)    let person2 = Person(value: ["id": 1234, "name": "Bowie"])                                realm.add(person2, update: .modified)}

You can also partially update an object by passing the primary key and a subset of the values to update:

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock:^{                [Person createOrUpdateModifiedInRealm:realm        withValue:@{@"_id": @123, @"dogs": @[@[@"Buster", @5]]}];}];
let realm = try! Realm()try! realm.write {                realm.create(Person.self,                 value: ["id": 123, "dogs": [["Buster", 5]]],                 update: .modified)}

You can update a realm map as you would a standard Dictionary:

let realm = try! Realm()let wolfie = realm.objects(Dog.self).where {    $0.name == "Wolfie"}.first!print("Wolfie's favorite park in New York is: \(wolfie.favoriteParksByCity["New York"])")XCTAssertTrue(wolfie.favoriteParksByCity["New York"] == "Domino Park")try! realm.write {    wolfie.favoriteParksByCity["New York"] = "Washington Square Park"    wolfie.favoriteParksByCity.updateValue("A Street Park", forKey: "Boston")    wolfie.favoriteParksByCity.setValue("Little Long Pond", forKey: "Seal Harbor")}XCTAssertTrue(wolfie.favoriteParksByCity["New York"] == "Washington Square Park")

You can insert elements into a MutableSet during write transactions to add them to the property. If you are working with multiple sets, you can also insert or remove set elements contained in one set from the other set. Alternately, you can mutate a set to contain only the common elements from both.

let realm = try! Realm()let dog = Dog()dog.name = "Maui"dog.currentCity = "New York"try! realm.write {    realm.add(dog)    dog.citiesVisited.insert(dog.currentCity)}try! realm.write {    dog.currentCity = "Toronto"    dog.citiesVisited.insert(dog.currentCity)}XCTAssertEqual(dog.citiesVisited.count, 2)try! realm.write {    dog.citiesVisited.formUnion(dog2.citiesVisited)}XCTAssertEqual(dog.citiesVisited.count, 3)try! realm.write {    dog.citiesVisited.subtract(dog2.citiesVisited)}XCTAssertEqual(dog.citiesVisited.count, 2)try! realm.write {    dog.citiesVisited.formIntersection(dog2.citiesVisited)}XCTAssertEqual(dog.citiesVisited.count, 0)

You can update an AnyRealmValue property through assignment, but you must specify the type of the value when you assign it. The Realm Swift SDK provides an AnyRealmValue enum that iterates through all of the types the AnyRealmValue can store.

let realm = try! Realm()let rex = realm.objects(Dog.self).where {    $0.name == "Rex"}.first!try! realm.write {            rex.companion = .object(Dog(value: ["name": "Regina"]))}

To update a property in an embedded object, modify the property in a write transaction. If the embedded object is null, updating an embedded object property has no effect.

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock: ^{    Contact *contact = [Contact objectInRealm:realm                                forPrimaryKey:[[RLMObjectId alloc] initWithString:@"5f481c21f634a1f4eeaa7268" error:nil]];    contact.address.street = @"Hollywood Upstairs Medical College";    contact.address.city = @"Los Angeles";    contact.address.postalCode = @"90210";    NSLog(@"Updated contact: %@", contact);}];
let realm = try! Realm()let idOfPersonToUpdate = 123guard let person = realm.object(ofType: Person.self, forPrimaryKey: idOfPersonToUpdate) else {    print("Person \(idOfPersonToUpdate) not found")    return}try! realm.write {            person.address?.street = "789 Any Street"    person.address?.city = "Anytown"    person.address?.postalCode = "12345"    print("Updated person: \(person)")}

To overwrite an embedded object, reassign the embedded object property of a party to a new instance in a write transaction.

RLMRealm *realm = [RLMRealm defaultRealm];[realm transactionWithBlock: ^{    Contact *contact = [Contact objectInRealm:realm                                forPrimaryKey:[[RLMObjectId alloc] initWithString:@"5f481c21f634a1f4eeaa7268" error:nil]];    Address *newAddress = [[Address alloc] init];    newAddress.street = @"Hollywood Upstairs Medical College";    newAddress.city = @"Los Angeles";    newAddress.country = @"USA";    newAddress.postalCode = @"90210";    contact.address = newAddress;    NSLog(@"Updated contact: %@", contact);}];
let realm = try! Realm()let idOfPersonToUpdate = 123guard let person = realm.object(ofType: Person.self, forPrimaryKey: idOfPersonToUpdate) else {    print("Person \(idOfPersonToUpdate) not found")    return}try! realm.write {    let newAddress = Address()    newAddress.street = "789 Any Street"    newAddress.city = "Anytown"    newAddress.country = "USA"    newAddress.postalCode = "12345"        person.address = newAddress    print("Updated person: \(person)")}

You can use Swift concurrency features to asynchronously update objects using an actor-isolated realm.

This function from the example RealmActor defined on the Use Realm with Actors page shows how you might update an object in an actor-isolated realm:

func updateTodo(_id: ObjectId, name: String, owner: String, status: String) async throws {    try await realm.asyncWrite {        realm.create(Todo.self, value: [            "_id": _id,            "name": name,            "owner": owner,            "status": status        ], update: .modified)    }}

And you might perform this update using Swift's async syntax:

let actor = try await RealmActor()// Read objects in functions isolated to the actor and pass primitive values to the callerfunc getObjectId(in actor: isolated RealmActor, forTodoNamed name: String) async -> ObjectId {    let todo = actor.realm.objects(Todo.self).where {        $0.name == name    }.first!    return todo._id}let objectId = await getObjectId(in: actor, forTodoNamed: "Keep it safe")try await actor.updateTodo(_id: objectId, name: "Keep it safe", owner: "Frodo", status: "Completed")

This operation does not block or perform I/O on the calling thread. For more information about writing to realm using Swift concurrency features, refer to Use Realm with Actors - Swift SDK.

You can make changes to a class projection's properties in a write transaction.

let person = realm.objects(PersonProjection.self).first(where: { $0.firstName == "Jason" })!try! realm.write {    person.firstName = "David"}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4