Search code examples
iosswiftrealmrealm-migration

Access list property in Realm migration


I'm trying to access a List<String> property in a migration block.

My database object looks as follows:

@objcMembers
public class Foo: Object {
    let bar: List<String> = .init()
}

In my migration block I'm trying to access bar, but can't seem to get it right:

static func migrateFoo(_ migration: RealmSwift.Migration) {
    migration.enumerateObjects(ofType: Foo.className()) { old, _ in
        let test = old?["bar"] as? List<String>
        let test2 = old?["bar"] as? [String]
        let test3 = old?["bar"]
    }
}

Both test and test2 are nil. The output of test3 show the following:

(lldb) po test3
▿ Optional<Any>
  - some : List<string> <0x600001fb5f80> (
    [0] someContent
)

What would I need to cast test3 to, to be able to access the list?

EDIT

I want to access the element in the bar property, hence I thought that casting the migration object's bar property to a List<String>, which is the data type after all, would be sufficient. In the end what I would like to have is this:

for element in test {
    print(element) // `element` should be a `String` here
}

Solution

  • I don't know what the full scope is of what your trying to do but a specific answer to the question would be:

    let test = [ old!["bar"] ]
    

    EDIT

    The OP added some additional information. The goal is to be able to access the values within the bar List property. Here's some quickie code that iterates over that list and outputs the index and the object (as a string) to the console.

    migration.enumerateObjects(ofType: Foo.className()) { oldItem, newItem in
        let dynamicBarList = oldItem?.dynamicList("stringList")
        if let list = dynamicBarList {
            let myArray = list._rlmArray
            let lastIndex = myArray.count - 1
    
            for index in 0...lastIndex {
                let object = myArray.object(at: index)
                let value = "\(object)" //make the NSTaggedPointerString a String
                print(index, value)
            }
        }
    }