user7718859
user7718859

Reputation:

how to load data from Realm List

I am loading messages from Realm database in the message list.

// loads all messages from database
    func loadMessages() {
        messages = List<Message>(realm.objects(Message.self))
        collectionView?.reloadData()
       }

Where messages is defined as:

var messages = List<Message>()

I defined realm instance as:

// realm instance
    let realm = try! Realm()

It was working fine with swift3 but when I am migrated to Swift 4, I am getting error:

Argument passed to call that takes no argument. Please help with this. enter image description here

Upvotes: 1

Views: 2293

Answers (3)

Mika
Mika

Reputation: 1276

See latest Realm Swift documentation about collections. List objects are used to represent relationships. These are most suitable for classes like Message in your code. For view controllers saving Resultsobject as member field would work well. If you need to be flexible about the collection type, or provide for example a base class for view controllers with different type of realm collections, then AnyRealmCollection type can be used.

Upvotes: 1

David Pasztor
David Pasztor

Reputation: 54706

If you look at the documentation of Realm's List, you can see that its only initializer doesn't take any input arguments. I don't really see any advantages of storing a property of type List outside a Realm object subclass, since you can achieve the same functionality using a native Array or you can stick to the auto-updating Results collection as well.

However, if you really want to convert an Array to a List, you can do so by creating an empty list, then appending the Arrays elements to it rather than trying to add the elements in an initializer.

let messages = List<Message>() // List is a reference type, so you can declare it as immutable and you can still add elements to it

func loadMessages() {
    messages.append(realm.objects(Message.self))
    collectionView?.reloadData()
}

Upvotes: 0

Ivan Smetanin
Ivan Smetanin

Reputation: 2039

You can define messages as an array var messages = [Message]() and load them like this:

messages: [Message] = realm.objects(Message.self).toArray()

Upvotes: 0

Related Questions