从Realm过滤结果

时间:2018-10-18 06:30:07

标签: swift realm

我已经在Realm中保存了坐标数据,并且试图将结果分成2个单独的ArrayCLLocationDegrees(纬度和经度),但是我不知道如何。我正在打印检索到的结果,所以我知道它们已成功保存/检索-控制台输出:

[0] Data {
    latitude = 37.33454847;
    longitude = -122.03611286;
    }, 
[1] Data {
    latitude = 37.33454218;
    longitude = -122.03638578;
    }, 
//and continues...

ViewController类(loadLocations函数)

func loadLocations() {
    theLocations = realm.objects(Data.self)
    print(theLocations)
    //This function gets called in the viewDidLoad()
}

数据类

class Data: Object {
    @objc dynamic var latitude: CLLocationDegrees()
    @objc dynamic var longitude: CLLocationDegrees()
}

我如何将纬度和经度分成各自的ArrayCLLocationDegrees?甚至是Array中的CLLocationDegrees,然后覆盖一条折线?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以这样:

我的项目中未设置Realm,因此我正在使用struct。

位置结构:

struct Locations {

    let latitude: Double
    let longitude: Double
}

    // Your Realm result Array
    var theLocations = [Locations]()

    // Adding Dummy Data into theLocations Array
    theLocations.append(Locations(latitude: 37.33454847, longitude: -122.03611286))
    theLocations.append(Locations(latitude: 37.33454218, longitude: -122.03638578))

    // latitude and longitude to store values
    var arrLat = [Double]()
    var arrLong = [Double]()

    // Looping  through theLocations Array and Seperate latitude and longitude to append to array
    theLocations.forEach{ location in
        arrLat.append(location.latitude)
        arrLong.append(location.longitude)
    }

希望这会对您有所帮助。

答案 1 :(得分:0)

您可以将Yes映射到Results<Data>,然后将它们放在数组中:

CLLocationCoordinate2D

但是,您并没有真正以这种方式充分利用Realm的潜力。领域let results = realm.objects(Data.self) // btw, Data is a terrible name. You should call it "Coordinate" let arrayOfCoordinates = Array(results.map { CLLocationCoorinate2D(latitude: $0.latitude, longitude: $0.longitude) }) // arrayOfCoordinates is of type [CLLocationCoordinate2D] 应该被延迟访问(即仅在需要时访问)。如果要立即将整个对象转换为数组,则基本上是将所有内容加载到内存中。我建议您直接使用Results返回的惰性集合:

map
相关问题