我已成功将plist文件中的数据读入表格视图。现在,我只想知道如何添加另一个"项目"用字符串"名称"和"位置"附接。
我正在寻找的是一种方法,发送一个字符串保存为" name"或"位置"对于一个新的"项目"。例如,如果我单击一个按钮,输入的信息将存储在一个新的"项目"下的plist文件中。
有人可以帮助我朝正确的方向发展吗?如果是你,你会做什么?
我使用的是Swift 3和Xcode 8.2.1
这是我的.plist文件: enter image description here
这是我用来获取" name"和"位置" "项目",以便我可以将其插入表格视图中:
CountA
答案 0 :(得分:4)
这是阅读和帮助的辅助结构。写plist:
用法:
//Reading :
let rootArray = PlistFile(named: "PlistFilename")?.array
let rootDictionary = PlistFile(named: "PlistFilename")?.dictionary
//Writing :
if let plistFile = PlistFile(named : "UserData") {
plistFile.array = yourArray
}
//or :
try? PlistFile(named : "UserData")?.write(yourArray)
代码:
struct PlistFile {
enum PlistError: Error {
case failedToWrite
case fileDoesNotExist
}
let name:String
var sourcePath:String? {
return Bundle.main.path(forResource: name, ofType: "plist")
}
var destPath:String? {
if let _ = sourcePath {
let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return (dir as NSString).appendingPathComponent("\(name).plist")
} else {
return nil
}
}
var dictionary : [String:Any]? {
get{
return getDictionary()
}
set{
if let newDict = newValue {
try? write(dictionary: newDict)
}
}
}
var array : [Any]? {
get{
return getArray()
}
set{
if let newArray = newValue {
try? write(array: newArray)
}
}
}
private let fileManager = FileManager.default
init?(named :String) {
self.name = named
guard let source = sourcePath, let destination = destPath, fileManager.fileExists(atPath: source) else {
return nil
}
if !fileManager.fileExists(atPath: destination) {
do {
try fileManager.copyItem(atPath: source, toPath: destination)
} catch let error {
print("Unable to copy file. ERROR: \(error.localizedDescription)")
return nil
}
}
}
private func getDictionary() -> [String:Any]? {
guard let destPath = self.destPath, fileManager.fileExists(atPath: destPath) else {
return nil
}
return NSDictionary(contentsOfFile: destPath) as? [String:Any]
}
private func getArray() -> [Any]? {
guard let destPath = self.destPath, fileManager.fileExists(atPath: destPath) else {
return nil
}
return NSArray(contentsOfFile: destPath) as? [Any]
}
func write(dictionary : [String:Any]) throws{
guard let destPath = self.destPath, fileManager.fileExists(atPath: destPath) else {
throw PlistError.fileDoesNotExist
}
if !NSDictionary(dictionary: dictionary).write(toFile: destPath, atomically: false) {
print("Failed to write the file")
throw PlistError.failedToWrite
}
}
func write(array : [Any] ) throws {
guard let destPath = self.destPath, fileManager.fileExists(atPath: destPath) else {
throw PlistError.fileDoesNotExist
}
if !NSArray(array: array).write(toFile: destPath, atomically: false) {
print("Failed to write the file")
throw PlistError.failedToWrite
}
}
}
答案 1 :(得分:3)
使用PropertyListSerialization保存重复动态字典的简单方法
let plistDict: [String: Any] = ["Key": "Value"]
//Write Data Into Plist
func writePlist(dictContent: [String: Any]) {
let url = URL(fileURLWithPath: PlistManager.path)
do {
let data = try Data(contentsOf: url)
var array = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
array.append(dictContent)
let writeData = try PropertyListSerialization.data(fromPropertyList: array, format: .xml, options:0)
try writeData.write(to: url)
} catch {
print(error)
}
}
答案 2 :(得分:2)
你可以试试这段代码:
class SavedTracks: NSObject,NSCoding {
var name: String
var location: String
required init(name:String="", location:String="") {
self.name = name
self.location = location
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "Name") as? String ?? ""
self.location = decoder.decodeObject(forKey: "location") as? String ?? ""
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey:"Name")
coder.encode(location, forKey:"location")
}
}
class DataModel: NSObject {
var saveTrack = [SavedTracks]()
override init(){
super.init()
print("document file path:\(documentsDirectory())")
print("Data file path:\(dataFilePath())")
}
//save data
func saveData() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(saveTrack, forKey: "userList")
archiver.finishEncoding()
data.write(toFile: dataFilePath(), atomically: true)
}
//read data
func loadData() {
let path = self.dataFilePath()
let defaultManager = FileManager()
if defaultManager.fileExists(atPath: path) {
let url = URL(fileURLWithPath: path)
let data = try! Data(contentsOf: url)
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
saveTrack = unarchiver.decodeObject(forKey: "userList") as! Array
unarchiver.finishDecoding()
}
}
func documentsDirectory()->String {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)
let documentsDirectory = paths.first!
return documentsDirectory
}
func dataFilePath ()->String{
return self.documentsDirectory().appendingFormat("/userList.plist")
}
}
class ViewController: UIViewController {
var dataModel = DataModel()
override func viewDidLoad() {
super.viewDidLoad()
onCreateData()
}
//create data
func onCreateData(){
dataModel.saveTrack.append(SavedTracks(name: "jack", location: "xxx"))
dataModel.saveTrack.append(SavedTracks(name: "tom", location: "yyyy"))
dataModel.saveTrack.append(SavedTracks(name: "rose", location: "zzz"))
}
@IBAction func saveData(_ sender: UIButton) {
dataModel.saveData()
print("succeed")
}
@IBAction func printData(_ sender: UIButton) {
dataModel.loadData()
print("succeed!", dataModel.saveTrack)
}
}