我是使用领域的新手,我试图将我的api响应保存在领域数据库中。为此,我阅读了文档并开始工作,我创建了Objects类,其中有我的变量,当我在领域应用程序中添加数据时因错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
而崩溃时,现在要在其中保存数据。这是我的对象类,
class SingleChatRealm: Object {
var actualNameFor_1_2_1_chat = ""
var isGroup : Bool = true
var isNewGroup : Bool = false
var lastMessage = ""
var lastMsgRead : Bool = false
var lastMsgTime = ""
var lastMsgTimeActual = ""
var name = ""
var profilePic = ""
var roomSID = ""
var unReadMsgsCount = 0
var twChannelObj : TCHChannel?
var members = [TCHMember]()
var messages = [TCHMessage]()
// @objc dynamic var group_info : [String:JSON]?
} 这就是我在领域中存储数据的方式,
let realm = try! Realm()
try! realm.write {
let newListing = SingleChatRealm()
for items in dateWiseSortedSingleRooms
{
newListing.actualNameFor_1_2_1_chat = items.actualNameFor_1_2_1_chat
newListing.isGroup = items.isGroup
newListing.isNewGroup = items.isNewGroup
newListing.lastMessage = items.lastMessage
newListing.lastMsgRead = items.lastMsgRead
newListing.lastMsgTime = items.lastMsgTime
newListing.lastMsgTimeActual = items.lastMsgTimeActual
newListing.members = items.members
newListing.messages = items.messages
newListing.name = items.name
newListing.profilePic = items.profilePic!
newListing.roomSID = items.roomSID
newListing.twChannelObj = items.twChannelObj
newListing.unReadMsgsCount = items.unReadMsgsCount
print(newListing)
self.realm.add(newListing)
}
}
我的应用程序在此行self.realm.add(newListing)
上崩溃,出现上述给定错误,为什么会这样?我在此缺少什么?
答案 0 :(得分:2)
可能有几个原因,
@objc dynamic var
。realm
对象在该类中是全局对象,否则请从self
中删除self.realm.add(newListing)
。newListing
变量的所有值都不是nil
(那些已经使用一些默认值初始化的变量)。TCHChannel
,TCHMember
和TCHMessage
的实际数据类型是什么? Realm
可能不支持这些类型。SingleChatRealm
类结构。在这种情况下,您必须删除旧的.realm
文件并创建一个新文件。答案 1 :(得分:0)
您刚刚创建了Realm的新实例,但是self.realm仍然为nil,您应该添加以下行:
self.realm = realm
您的代码:
let realm = try! Realm()
self.realm = realm
try! realm.write {
let newListing = SingleChatRealm()
for items in dateWiseSortedSingleRooms
{
newListing.actualNameFor_1_2_1_chat = items.actualNameFor_1_2_1_chat
newListing.isGroup = items.isGroup
newListing.isNewGroup = items.isNewGroup
newListing.lastMessage = items.lastMessage
newListing.lastMsgRead = items.lastMsgRead
newListing.lastMsgTime = items.lastMsgTime
newListing.lastMsgTimeActual = items.lastMsgTimeActual
newListing.members = items.members
newListing.messages = items.messages
newListing.name = items.name
newListing.profilePic = items.profilePic!
newListing.roomSID = items.roomSID
newListing.twChannelObj = items.twChannelObj
newListing.unReadMsgsCount = items.unReadMsgsCount
print(newListing)
self.realm.add(newListing)
}
}