您好我只是想知道如何从自定义NSObject类中提取数据我的位置NSObject类下面是我的NSObject类(假设数据已经从其他类填充)
import Foundation
class LocationModel: NSObject {
//properties
var name: String?
var address: String?
var latitude: String?
var longitude: String?
//empty constructor
override init()
{
}
//construct with @name, @address, @latitude, and @longitude parameters
init(name: String, address: String, latitude: String, longitude: String) {
self.name = name
self.address = address
self.latitude = latitude
self.longitude = longitude
}
//prints object's current state
override var description: String {
return "Name: \(name), Address: \(address), Latitude: \(latitude), Longitude: \(longitude)"
}
}
这是我的循环提取数据(我不知道)
let MapPoint : LocationModel = LocationModel()
for item in MapPoint {
let name = MapPoint.name
let latitude = MapPoint.latitude
let longitude = MapPoint.longitude
print(name, latitude, longtitude)
}
答案 0 :(得分:0)
首先,删除默认初始值设定项并将属性声明为常量和非选项。好处是编译器将帮助您防止空数据。
class LocationModel: NSObject {
//properties
let name, address, latitude, longitude: String
// construct with @name, @address, @latitude, and @longitude parameters
init(name: String, address: String, latitude: String, longitude: String) {
self.name = name
self.address = address
self.latitude = latitude
self.longitude = longitude
}
//prints object's current state
override var description: String {
return "Name: \(name), Address: \(address), Latitude: \(latitude), Longitude: \(longitude)"
}
现在迭代的对象必须是[LocationModel]
let mapPoints = [LocationModel(name:"name1", address:"address1", latitude:"latitude1", longitude:"longitude1"),
LocationModel(name:"name2", address:"address2", latitude:"latitude2", longitude:"longitude2"),
LocationModel(name:"name3", address:"address3", latitude:"latitude3", longitude:"longitude3")]
for item in mapPoints {
let name = item.name
let latitude = item.latitude
let longitude = item.longitude
print(name, latitude, longitude)
}
如果地址属性可能丢失,则使用默认值声明初始化程序,并将空字符串视为无值
init(name: String, address: String = "", latitude: String, longitude: String) {...