45

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

Andy
  • 1,801
  • 3
  • 22
  • 33

1 Answers1

86

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.

Thomas Goyne
  • 8,010
  • 32
  • 30
  • 1
    Thanks, exactly what I was looking for. I had to call it with objectForPrimaryKey(Book.self, key: prevBook.nextID) – Andy Jun 03 '15 at 04:57
  • 3
    What is the equivalent for Java (Android)? – mm2001 Mar 28 '16 at 22:35
  • 1
    ... and what is equivalent for Javascript (React Native) too? – Szczepan Hołyszewski Apr 15 '16 at 20:02
  • 5
    For anyone looking for this still, know that the method has been updated to `object(ofType:forPrimaryKey:)`. The above example is now `Realm().object(ofType: Book.self, forPrimaryKey: prevBook.nextId)` – Salem Mar 30 '17 at 12:13