【发布时间】:2017-05-30 19:20:54
【问题描述】:
我已成功地将我的 plist 文件中的数据读取到表视图中。现在,我只想知道如何添加另一个带有字符串“名称”和“位置”的“项目”。
我正在寻找的是一种发送字符串以保存为新“项目”的“名称”或“位置”的方法。例如,如果我单击一个按钮,输入的信息将存储在新“项目”下的 plist 文件中。
有人可以帮助我朝着正确的方向前进吗?如果是你,你会怎么做?
我正在使用 Swift 3 和 Xcode 8.2.1
这是我的 .plist 文件: enter image description here
这是我用于获取“项目”的“名称”和“位置”的代码,以便我可以将其插入到表格视图中:
struct SavedTracks {
let name: String
let location: String
}
extension SavedTracks {
enum ErrorType: Error {
case noPlistFile
case cannotReadFile
}
/// Load all the elements from the plist file
static func loadFromPlist() throws -> [SavedTracks] {
// First we need to find the plist
guard let file = Bundle.main.path(forResource: "SkiTracks", ofType: "plist") else {
throw ErrorType.noPlistFile
}
// Then we read it as an array of dict
guard let array = NSArray(contentsOfFile: file) as? [[String: AnyObject]] else {
throw ErrorType.cannotReadFile
}
// Initialize the array
var elements: [SavedTracks] = []
// For each dictionary
for dict in array {
// We implement the element
let element = SavedTracks.from(dict: dict)
// And add it to the array
elements.append(element)
}
// Return all elements
return elements
}
/// Create an element corresponding to the given dict
static func from(dict: [String: AnyObject]) -> SavedTracks {
let name = dict["name"] as! String
let location = dict["location"] as! String
return SavedTracks(name: name,
location: location)
}
}
【问题讨论】:
标签: ios arrays swift xcode swift3