Realm write transaction failing, despite being in transaction
The trouble was I was using a plain Realm
object with no special configuration. Since I am using Realm Mobile Platform, I needed to create a Realm
object with the same config each time I want to write to that DB:
let configuration = Realm.Configuration(
syncConfiguration: SyncConfiguration(user: user, realmURL: URL(string: "realm://127.0.0.1:9080/~/speciail")!)
)
self.realm = try! Realm(configuration: configuration)
//now do the write transaction!
It took a bit of refactoring, but I have it now. My thanks to those of you who took the time to help me.
How much time does Realm take for a write transaction to perform an Object add?
If you're not seeing the updates to a Realm file straight away, you can call refresh
on the RLMRealm
/ Realm
object to manually force a refresh.
Normally changes are updated across all Realm objects on all threads on the next iteration of the run loop (Which you would also achieve by introducing a time delay like you have above!), but calling refresh
will cause that version of the Realm object to update before the current iteration of the run loop has completed.
realm commit write error - Can't commit a non-existing write transaction
In your example you called commitWrite
without having called beginWrite
. You cannot commit a write transaction because you did not start one. Either start a write transaction or delete the commitWrite line.
Start transaction and commit it
self.realm.beginWrite()
self.realm.add(ConnectionState)
try! self.realm.commitWrite()Delete commitWrite
try! self.realm.write {
self.realm.add(ConnectionState)
}
The Realm docs have two examples of adding data to the database.
Use the
realm.write
method// Use them like regular Swift objects
let myDog = Dog()
myDog.name = "Rex"
myDog.age = 1
print("name of dog: \(myDog.name)")
// Get the default Realm
let realm = try! Realm()
// Query Realm for all dogs less than 2 years old
let puppies = realm.objects(Dog.self).filter("age < 2")
puppies.count // => 0 because no dogs have been added to the Realm yet
// Persist your data easily
try! realm.write {
realm.add(myDog)
}Use
realm.beginWrite()
andrealm.commitWrite()
to start the write transaction and commit data to the databaselet realm = try! Realm()
// Break up the writing blocks into smaller portions
// by starting a new transaction
for idx1 in 0..<1000 {
realm.beginWrite()
// Add row via dictionary. Property order is ignored.
for idx2 in 0..<1000 {
realm.create(Person.self, value: [
"name": "\(idx1)",
"birthdate": Date(timeIntervalSince1970: TimeInterval(idx2))
])
}
// Commit the write transaction
// to make this data available to other threads
try! realm.commitWrite()
}
Realm - Why are notification blocks triggered when a write transaction begins?
If a write was made on a different thread between when the Realm was last refreshed and when you begin a write transaction, beginning the write transaction will implicitly refresh the Realm first. If this results in anything changing, any applicable notifications will be sent immediately to notify you of the change.
Realm is already in a write transaction if I execute two transactions in the same method
If I understand your problem correctly, you want to eliminate/remove first two records (if there are) and insert new record at the end of the list. Try this
fun savedAddresses(name: String, address: String) {
realm.executeTransaction { realm ->
val addressToSave = realm.createObject(RecentAddress::class.java)
addressToSave.name = name
addressToSave.street = address
//insert the record at the end of the list
realm.insert(addressToSave)
}
deleteOldRecords()
}
fun deleteOldRecords() {
realm.executeTransaction { realm ->
val recentAddressList = realm.where(RecentAddress::class.java).findAll()
if(recentAddressList.size > 2){
for(i in 0..1) {
recentAddressList.deleteFromRealm(i)
}
}
}
}
please correct me if i understood wrong.
Inconsistent behaviour in Realm write
[[RLMRealm defaultRealm] transactionWithBlock:^{
RLMRealm *realm = [RLMRealm defaultRealm];
//NSArray *scores contains all score objects to be added
Game game = [Game createOrUpdateInRealm:realm withValue:aGame];
NSMutableArray *rlmScores = [NSMutableArray array];
for (Score *aScore in scores) {
Score *rlmScore = [Score createOrUpdateInRealm:realm withValue:aScore];
[rlmScores addObject:rlmScore];
}
[game.scores addObjects:rlmScores];
//Pass game to next ViewController for display
}];
Adding the Realm score objects to an array and then adding the array to game.scores RLMArray worked. I have no idea why this worked and adding the objects one by one in a loop won't work. I am posting the solution that worked for me if anyone else runs into a similar problem.
Please feel free to provide a better solution or an explanation for the issue.
Related Topics
How to Reconnect Akplayer and Akmixer After Audiokit.Stop()
Exc Bad Access While Creating a New Characterset
My UIcollectionview Does Not Scroll Smoothly Using Swift
Do Protocols Have an Effect on The Retain Count
How to Make First Responder in Swiftui Macos
On Demand Resources "0 Asset Packs"
Trouble Calling a Method in an Init
Firebase Swift 3 Get List of Child in a Array
Arkit/Scenekit on iOS 14 Throws New Warning (Metal)
Swiftui Navigationview Not See Image
Reload Tableview After Clicking The Button Present Inside One of The Tableview Cell in Swift
Swift Initialization Rule Confusion
Swift: Trunc a Floating Number to Show It in a Label
Actions Assigned to Nsmenuitem Dont Seem to Work
How to Do Imageview.Startanimating() with Completion in Swift