Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to retrieve a single object from Realm database

I am absolutely loving Realm (0.92) in combination with Swift but have a question about reading an object from the database. My goal is to retrieve a single object with a known, unique ID (which also happens to be the primary key.

All the documentation appears to be oriented around queries for multiple objects which are then filtered. In this case I know the object ID and, since it is known to be unique, would like to retrieve it directly.

My current approach is as follows:

Realm().objects(Book).filter("id == %@", prevBook.nextID).first 

This seems heavy-handed. Documentation from prior versions suggest that there is a more direct way but I can't seem to locate it in the documentation.

The problem with my current approach is that it is crashing with an exception on the following function:

public func filter(predicateFormat: String, _ args: CVarArgType...) -> Results<T> 

The exception is mysteriously reported as:

EXC_BAD_ACCESS (code=1, address=0xedf)

Any suggestions are very welcome.

Anticipating one line of questioning: I have confirmed that replacing prevBook.nextID with a known, good ID does not solve the problem

like image 543
Andy Avatar asked Jun 03 '15 03:06

Andy


People also ask

How do I use a Realm database?

To add the Realm library to the project, first add the classpath dependency to the project level build. gradle file. Then apply the realm-android plugin to the top of the application level build. gradle file.

How do you create a Realm object?

To define a Realm object in your application, create a subclass of RealmObject or implement RealmModel. All Realm objects must provide an empty constructor. All Realm objects must use the public visibility modifier in Java or the open visibility modifier in Kotlin.

How do you delete an object from a Realm?

Select a realm and click the Edit button. The Edit Realm wizard displays. Click Next to move to the Realm Objects page where you can click Remove to delete objects from the realm. Click Done.


1 Answers

object(ofType:forPrimaryKey:) is what you're looking for: Realm().object(ofType: Book.self, forPrimaryKey: prevBook.nextId). There's no simpler way than filter().first if you need to search for the object by something other than the primary key.

like image 123
Thomas Goyne Avatar answered Oct 24 '22 22:10

Thomas Goyne