In my Realm DB for ChatMessage I have the following data object:
When i follow the tutorial on retrieving data/query :
let realm = try! Realm()
let specificPerson = realm.object(ofType: ChatMessage.self,
forPrimaryKey: ObjectId("6369ee9db15ac444f96eb5d6"))
print(specificPerson!.author as String)
I receive fatal error Nil, it cannot find anything. from the line
print(specificPerson!.author as String)
LiveChat/ChatView.swift:59: Fatal error: Unexpectedly found nil while unwrapping an Optional value
When I do a broader query for all,
let chatM = realm.objects(ChatMessage.self)
print(chatM)
print(type(of: chatM))
I receive empty object
Results<ChatMessage> <0x7fe4d163efa0> (
)
Results<ChatMessage>
I am adding the Chat messages Via
@ObservedResults(ChatMessage.self,
sortDescriptor: SortDescriptor(keyPath: "timeStamp", ascending: true)) var messages
private func addMessage(){
let message = ChatMessage(room: room, author: userName, text: messageText)
$messages.append(message)
messageText = ""
}
CodePudding user response:
Regarding your updated code:
So yes, you are indeed creating the objects (using the .append(_:)
method on an @ObservedResults
collection) in a correct way. This means that you are likely opening the wrong realm database when you're querying for the objects. Please have a look at Realm's documentation regarding realm configuration, specifically on how to set the default configuration. Calling try! Realm()
without any parameters will use this default configuration to open the database.
Original reply
If let chatM = realm.objects(ChatMessage.self)
returns an empty Results
object, the realm you're querying does not contain any objects of the ChatMessage
type. It's as simple as that. Logically, let specificPerson = realm.object(ofType: ChatMessage.self, forPrimaryKey: ObjectId("6369ee9db15ac444f96eb5d6"))
would then also return nil.
Without seeing how and where you're creating the missing ChatMessage
objects, it's hard to say what's going wrong. Some common missteps:
- You are querying the wrong realm database: If you are only every accessing realm through
let realm = try! Realm()
this shouldn't be a problem. - You haven't actually added any
ChatMessage
object to the realm database: Simply initializing an object is not enough, You need to explicitly add objects to the Realm database using eitherRealm.create()
orRealm.add()
:
let realm = try! Realm()
let exampleObject = ChatMessage()
print(realm.objects(ChatMessage.self).count) // Prints "0"
// Add to the realm using either create() or add()
realm.add(exampleObject)
print(realm.objects(ChatMessage.self).count) // Prints "1"