Get single object from primary key of realm object - ios

I have realm object which is in objective-c class (our project is mix&match between swift and objective-c)
I know that I can access
[ClassName objectForPrimaryKey:] in objc
but I don't know how can I use this method in swift file?
is this possible?
Thanks.

In case of Swift you should use the following code:
let realm = try! Realm()
let object = realm.object(ofType: ClassName.self, forPrimaryKey: primaryKey)

In case if you are using Realm as an Objective-C library in Swift, then:
let object = ClassName(forPrimaryKey: primaryKey)

Related

Beginner in Realm Swift - How to instantiate a new Realm in SwiftUI

I have a class DataEntry that I want to store instances of in a Realm database, but i'm having issue instantiating a Realm. Here is my DataEntry class:
class DataEntry: Object {
#objc dynamic var id = 0
#objc dynamic var exercise = ""
#objc dynamic var weightLBS = 0
#objc dynamic var averageBarSpeed = 0
#objc dynamic var topBarSpeed = 0
}
Some context as to what I'll be using it for:
I'd like to have functions to write and delete instances of a DataEntry, but the documentation on that seems fairly simple.
Adding new dataEntry would be done by a user inputing data into a form
Deleting dataEntrys will simply be a button
Planning on reading the data to create graphs to track performance over time
The issue I'm having is instantiating a new Realm, and using the appropriate error handling. I've found a few simpler examples, but they all throw errors so i'm assuming there's something i'm missing. I know you're not supposed to use try!, so I'm wondering, what is a simple way to instantiate a new Realm, so I can then read/write/delete DataEntry's to the Realm Database.
This one gives me multiple "Expected Declaration" errors in lines 1 and 3.
do {
let realm = try Realm()
} catch let error as NSError {
// handle error
}
This one gives me an "Expected Declaration" error on line 1
try {
let realm = try Realm()
} catch {
print(error.localizedDescription)
}
Any additional pointers on how to best set up this would be amazing, wether or not I should have a RealmManager class that would aid in error handling. I've seen in some cases people create extensions of Realm, but this is a little too advanced for me right now.
Background in CS, but brand new to both Swift and Realm for context.
Edit/Update:
Quick clarification, I'm having issues with instantiating a Realm. Not a Realm object. I've updated above to be more clear.
To clarify my question, I'm getting errors for what appears to be good code above, so I assume I have it in the wrong place. I get errors when its inside the DataEntry class, when its inside of a view, and at the top level of a SwiftUI file. Any advice on where I should include the c ode for the instantiation would be great!
I am not sure if this will help but knowing where to put things within a project can sometimes help understand the flow.
So I created a realm project in XCode that writes a person object with the name of Jay to realm when button 0 is clicked. Then when button 1 is clicked, it retrieves that data and prints to console.
There's no error checking here and I am force unwrapping an optional so don't do that in a real app.
import Cocoa
import RealmSwift
class PersonClass: Object {
#Persisted var name = ""
}
class ViewController: NSViewController {
#IBAction func button0Action(_ sender: Any) {
let realm = try! Realm()
let jay = PersonClass()
jay.name = "Jay"
try! realm.write {
realm.add(jay)
}
}
#IBAction func button1Action(_ sender: Any) {
let realm = try! Realm()
let jay = realm.objects(PersonClass.self).where { $0.name == "Jay" }.first!
print(jay.name) //outputs "Jay" to console
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
The project starts with importing RealmSwift and then the Realm object(s) are defined outside of any other classes, so they are at a high level.
Then we have the ViewController with two button actions - as you can see, within each action function, we access realm with
let realm = try! Realm()
and then interact with realm. When that function exits, the realm object is deallocated so it's a safe way to work with Realm and not leave it 'connected'.
Some developers create a singleton or a RealmService class to interact with Realm but singletons can be tricky. I suggest initially going with the pattern shown above (and in the docs).
there has a better way to update and append a new record to Realm in the latest version.
#ObservedResults(Group.self) var groups
$groups.append(Group())
TextField("New name", text: $item.name)
The documentation is here, please take some time to read it.
If it is hard for you, I suggest at least finishing this video by code along with her. LINK

Swift 3 : Ambiguous use of mutablecopy

When i migrated the code from swift 2.3 to 3.0, its throwing an error as below:
let dictionary = (self.testArray!.object(at: i) as AnyObject).mutableCopy()
How to resolve this issue.
Do not use mutableCopy in Swift. The var keyword makes objects mutable
var dictionary = self.testArray![i] as! [String:Any]
And don't use Foundation collection types (NSArray / NSDictionary) in Swift either.
Use native types.

Fetching Single Row in Realm

I'm having a problem in fetching a single row in a table. My problem is that I cannot display it. Here is what I have so far
let feed: RLMObject = FeedsModel.objectsWhere("id = 1").firstObject()!
print(feed.title)
Thank you very much!
You should fetch the single object with primary key like this:
let realm = try! Realm()
let feeds = realm.objectForPrimaryKey(FeedsModel.self, key: "1")
You're attempting to access the title property of RLMObject, which doesn't exist. This property only exists on FeedsModel. Instead, you should cast the object as a FeedsModel:
let feed = FeedsModel.objectsWhere("id = 1").firstObject() as! FeedsModel
print(feed.title)
If you'd like to use Realm from Swift with nicer generics, I'd encourage you to consider using Realm Swift instead of Realm Objective-C.

Realm: rearranging list of objects

Please, tell me, how to rearrange items of Realm's list of objects by index? I.e. I'm looking something like
let movingElement = array[oldIndex]
array.removeAtIndex(oldIndex)
array.insert(movingElement, atIndex: newIndex)
if it was with a casual Swift array of something.
But for List in Realm I can not do the same thing:
let realm = try! Realm()
var all = try! Realm().objects(element)
realm.write {
all.removeAtIndex() // all of type
Another option is to
let realm = try! Realm()
let element = try! Realm().objects(Element)[oldIndex]
realm.write{
realm.delete(element)
realm.add(...) // How to set index to place new object at?
}
But how to insert element in proper place? May be there is a proper method how to move elements of realm of the same type (class) by index?
Thanks in advance!
You cannot do it with query results, as they are unordered (or in a specific order if you sort them). But if you put them into Realm List (which you can store as member in a Realm object), then you can use both move and swap methods to reorder elements.
Here is the API docs for the the List type: https://realm.io/docs/swift/latest/api/Classes/List.html

Realm partial update using createOrUpdate doesn't work

I am trying to use Realm for my iOS app. When updating the local Realm DB using createOrUpate, it rewrites the unprovided properties with default values, rather than keep them unchanged. The Realm I use is up to date, 0.93. Anybody has the same issue?
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
for matchedUser in matchedUsers {
let newMatchedUser = MatchedUser()
newMatchedUser.objectId = matchedUser.objectId
newMatchedUser.username = matchedUser.username
newMatchedUser.email = matchedUser.email
newMatchedUser.fullname = matchedUser["fullname"] as! String
//they are other properties unprovided here.
MatchedUser.createOrUpdateInDefaultRealmWithValue(newMatchedUser)
}
realm.commitWriteTransaction()
So, I figured out what the issue was. It turns out you cannot user newMachtedUser to update the DB because it will initialize it first and the default values will be provided for this initialization process. The right way is to using individual values to update, or create an dictionary/array for that update.

Resources