Ios 如何在SWIFT中向Plist添加字典

Ios 如何在SWIFT中向Plist添加字典,ios,swift,plist,Ios,Swift,Plist,我有一本如下类型的字典 var favoriteGooglelocations = [Int:GoogleItems]() 其中GoogleItems是类 class GoogleItems: NSObject { var name:String? var address:String? var distance : String? var googleLocation: CLLocation? var isStar : Bool? } 我写信给字

我有一本如下类型的字典

var favoriteGooglelocations = [Int:GoogleItems]()
其中GoogleItems是类

class GoogleItems: NSObject {

    var name:String?
    var address:String?
    var distance : String?
    var googleLocation: CLLocation?
    var isStar : Bool?

}
我写信给字典是这样写的:

var newLocation = GoogleItems()
newLocation.name = locations[sender.tag].name
newLocation.address = locations[sender.tag].address
newLocation.distance = locations[sender.tag].distance
favoriteGooglelocations[sender.tag] = newLocation
当我试图编写这本字典时,它会给我编译时错误
favoriteGooglelocations.WriteFile(路径,原子性:true)

错误:>[Int:GoogleItems]没有名为的成员 写文件

已更新: 我正在写的路径是

 let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

 let documentDirectory = paths[0] as! String

 path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")

如何将字典添加到PList,还有其他方法吗?

您需要将字典转换为
NSDictionary
,以便使用
writeToFile

试着用这个来投

let succeed = (favoriteGooglelocations as NSDictionary).writeToFile(path, atomically: true)
如果success为false,请检查您的GoogleItems类,它应该符合
NSCoding

更新,这是我测试的代码,您可以参考它

import UIKit
import CoreLocation
设置您的
GoogleItems
是否符合NSCoding

class GoogleItems: NSObject,NSCoding {
override init() {}
var name:String?
var address:String?
var distance : String?
var googleLocation: CLLocation?
var isStar : Bool?
required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as? String
    self.address = aDecoder.decodeObjectForKey("address") as? String
    self.distance = aDecoder.decodeObjectForKey("distance") as? String
    self.googleLocation = aDecoder.decodeObjectForKey("googleLocation") as? CLLocation
    self.isStar = aDecoder.decodeObjectForKey("isStar") as? Bool
}
func encodeWithCoder(aCoder: NSCoder) {
    if name != nil{  aCoder.encodeObject(name, forKey: "name")}
    if address != nil{ aCoder.encodeObject(address, forKey: "address")}
    if distance != nil { aCoder.encodeObject(distance, forKey: "distance")}
    if googleLocation != nil { aCoder.encodeObject(googleLocation, forKey: "googleLocation")}
    if isStar != nil {aCoder.encodeBool(isStar!, forKey: "isStar")}
}
}
然后写入文件

    var favoriteGooglelocations = [Int:GoogleItems]()
    var item = GoogleItems()
    item.isStar = true
    item.name = "name"
    item.address = "address"
    item.googleLocation = nil
    item.distance = "23"
    favoriteGooglelocations[1] = item
    let dic = favoriteGooglelocations as NSDictionary
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentDirectory = paths[0] as! String
    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let succeed = NSKeyedArchiver.archiveRootObject(dic, toFile: path)
    println(succeed)
从文件中读取

     let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

    let documentDirectory = paths[0] as! String

    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let dic = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Int:GoogleItems]
    if(dic != nil){
        for (key,value) in dic!{
            let item = value
            println(item.name)
            println(item.address)
        }

    }

您需要将字典转换为
NSDictionary
,以便可以使用
writeToFile

试着用这个来投

let succeed = (favoriteGooglelocations as NSDictionary).writeToFile(path, atomically: true)
如果success为false,请检查您的GoogleItems类,它应该符合
NSCoding

更新,这是我测试的代码,您可以参考它

import UIKit
import CoreLocation
设置您的
GoogleItems
是否符合NSCoding

class GoogleItems: NSObject,NSCoding {
override init() {}
var name:String?
var address:String?
var distance : String?
var googleLocation: CLLocation?
var isStar : Bool?
required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as? String
    self.address = aDecoder.decodeObjectForKey("address") as? String
    self.distance = aDecoder.decodeObjectForKey("distance") as? String
    self.googleLocation = aDecoder.decodeObjectForKey("googleLocation") as? CLLocation
    self.isStar = aDecoder.decodeObjectForKey("isStar") as? Bool
}
func encodeWithCoder(aCoder: NSCoder) {
    if name != nil{  aCoder.encodeObject(name, forKey: "name")}
    if address != nil{ aCoder.encodeObject(address, forKey: "address")}
    if distance != nil { aCoder.encodeObject(distance, forKey: "distance")}
    if googleLocation != nil { aCoder.encodeObject(googleLocation, forKey: "googleLocation")}
    if isStar != nil {aCoder.encodeBool(isStar!, forKey: "isStar")}
}
}
然后写入文件

    var favoriteGooglelocations = [Int:GoogleItems]()
    var item = GoogleItems()
    item.isStar = true
    item.name = "name"
    item.address = "address"
    item.googleLocation = nil
    item.distance = "23"
    favoriteGooglelocations[1] = item
    let dic = favoriteGooglelocations as NSDictionary
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentDirectory = paths[0] as! String
    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let succeed = NSKeyedArchiver.archiveRootObject(dic, toFile: path)
    println(succeed)
从文件中读取

     let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

    let documentDirectory = paths[0] as! String

    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let dic = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Int:GoogleItems]
    if(dic != nil){
        for (key,value) in dic!{
            let item = value
            println(item.name)
            println(item.address)
        }

    }

您需要将字典转换为
NSDictionary
,以便可以使用
writeToFile

试着用这个来投

let succeed = (favoriteGooglelocations as NSDictionary).writeToFile(path, atomically: true)
如果success为false,请检查您的GoogleItems类,它应该符合
NSCoding

更新,这是我测试的代码,您可以参考它

import UIKit
import CoreLocation
设置您的
GoogleItems
是否符合NSCoding

class GoogleItems: NSObject,NSCoding {
override init() {}
var name:String?
var address:String?
var distance : String?
var googleLocation: CLLocation?
var isStar : Bool?
required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as? String
    self.address = aDecoder.decodeObjectForKey("address") as? String
    self.distance = aDecoder.decodeObjectForKey("distance") as? String
    self.googleLocation = aDecoder.decodeObjectForKey("googleLocation") as? CLLocation
    self.isStar = aDecoder.decodeObjectForKey("isStar") as? Bool
}
func encodeWithCoder(aCoder: NSCoder) {
    if name != nil{  aCoder.encodeObject(name, forKey: "name")}
    if address != nil{ aCoder.encodeObject(address, forKey: "address")}
    if distance != nil { aCoder.encodeObject(distance, forKey: "distance")}
    if googleLocation != nil { aCoder.encodeObject(googleLocation, forKey: "googleLocation")}
    if isStar != nil {aCoder.encodeBool(isStar!, forKey: "isStar")}
}
}
然后写入文件

    var favoriteGooglelocations = [Int:GoogleItems]()
    var item = GoogleItems()
    item.isStar = true
    item.name = "name"
    item.address = "address"
    item.googleLocation = nil
    item.distance = "23"
    favoriteGooglelocations[1] = item
    let dic = favoriteGooglelocations as NSDictionary
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentDirectory = paths[0] as! String
    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let succeed = NSKeyedArchiver.archiveRootObject(dic, toFile: path)
    println(succeed)
从文件中读取

     let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

    let documentDirectory = paths[0] as! String

    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let dic = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Int:GoogleItems]
    if(dic != nil){
        for (key,value) in dic!{
            let item = value
            println(item.name)
            println(item.address)
        }

    }

您需要将字典转换为
NSDictionary
,以便可以使用
writeToFile

试着用这个来投

let succeed = (favoriteGooglelocations as NSDictionary).writeToFile(path, atomically: true)
如果success为false,请检查您的GoogleItems类,它应该符合
NSCoding

更新,这是我测试的代码,您可以参考它

import UIKit
import CoreLocation
设置您的
GoogleItems
是否符合NSCoding

class GoogleItems: NSObject,NSCoding {
override init() {}
var name:String?
var address:String?
var distance : String?
var googleLocation: CLLocation?
var isStar : Bool?
required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as? String
    self.address = aDecoder.decodeObjectForKey("address") as? String
    self.distance = aDecoder.decodeObjectForKey("distance") as? String
    self.googleLocation = aDecoder.decodeObjectForKey("googleLocation") as? CLLocation
    self.isStar = aDecoder.decodeObjectForKey("isStar") as? Bool
}
func encodeWithCoder(aCoder: NSCoder) {
    if name != nil{  aCoder.encodeObject(name, forKey: "name")}
    if address != nil{ aCoder.encodeObject(address, forKey: "address")}
    if distance != nil { aCoder.encodeObject(distance, forKey: "distance")}
    if googleLocation != nil { aCoder.encodeObject(googleLocation, forKey: "googleLocation")}
    if isStar != nil {aCoder.encodeBool(isStar!, forKey: "isStar")}
}
}
然后写入文件

    var favoriteGooglelocations = [Int:GoogleItems]()
    var item = GoogleItems()
    item.isStar = true
    item.name = "name"
    item.address = "address"
    item.googleLocation = nil
    item.distance = "23"
    favoriteGooglelocations[1] = item
    let dic = favoriteGooglelocations as NSDictionary
    let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    let documentDirectory = paths[0] as! String
    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let succeed = NSKeyedArchiver.archiveRootObject(dic, toFile: path)
    println(succeed)
从文件中读取

     let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)

    let documentDirectory = paths[0] as! String

    let  path = documentDirectory.stringByAppendingPathComponent("Favorites.plist")
    let dic = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? [Int:GoogleItems]
    if(dic != nil){
        for (key,value) in dic!{
            let item = value
            println(item.name)
            println(item.address)
        }

    }

更新:Xcode 7.2•Swift 2.1.1

您可以按如下方式使用NSKeyedArchiver.archiveRootObject():

let dictionary:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]

let documentDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let fileURL = documentDirectoryURL.URLByAppendingPathComponent("dictionary.plist")
if NSKeyedArchiver.archiveRootObject(dictionary, toFile: fileURL.path!) {
    print(true)
}

if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [String:String] {
    print(loadedDic)   // "["key1": "value1", "key2": "value2", "key3": "value3"]\n"
}
如果GoogleItems符合NSCoding

if NSKeyedArchiver.archiveRootObject(favoriteGooglelocations, toFile: fileURL.path!) {
    if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Int:GoogleItems] {
        println(loadedDic)
    }
}

更新:Xcode 7.2•Swift 2.1.1

您可以按如下方式使用NSKeyedArchiver.archiveRootObject():

let dictionary:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]

let documentDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let fileURL = documentDirectoryURL.URLByAppendingPathComponent("dictionary.plist")
if NSKeyedArchiver.archiveRootObject(dictionary, toFile: fileURL.path!) {
    print(true)
}

if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [String:String] {
    print(loadedDic)   // "["key1": "value1", "key2": "value2", "key3": "value3"]\n"
}
如果GoogleItems符合NSCoding

if NSKeyedArchiver.archiveRootObject(favoriteGooglelocations, toFile: fileURL.path!) {
    if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Int:GoogleItems] {
        println(loadedDic)
    }
}

更新:Xcode 7.2•Swift 2.1.1

您可以按如下方式使用NSKeyedArchiver.archiveRootObject():

let dictionary:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]

let documentDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let fileURL = documentDirectoryURL.URLByAppendingPathComponent("dictionary.plist")
if NSKeyedArchiver.archiveRootObject(dictionary, toFile: fileURL.path!) {
    print(true)
}

if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [String:String] {
    print(loadedDic)   // "["key1": "value1", "key2": "value2", "key3": "value3"]\n"
}
如果GoogleItems符合NSCoding

if NSKeyedArchiver.archiveRootObject(favoriteGooglelocations, toFile: fileURL.path!) {
    if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Int:GoogleItems] {
        println(loadedDic)
    }
}

更新:Xcode 7.2•Swift 2.1.1

您可以按如下方式使用NSKeyedArchiver.archiveRootObject():

let dictionary:[String:String] = ["key1" : "value1", "key2":"value2", "key3":"value3"]

let documentDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
let fileURL = documentDirectoryURL.URLByAppendingPathComponent("dictionary.plist")
if NSKeyedArchiver.archiveRootObject(dictionary, toFile: fileURL.path!) {
    print(true)
}

if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [String:String] {
    print(loadedDic)   // "["key1": "value1", "key2": "value2", "key3": "value3"]\n"
}
如果GoogleItems符合NSCoding

if NSKeyedArchiver.archiveRootObject(favoriteGooglelocations, toFile: fileURL.path!) {
    if let loadedDic = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Int:GoogleItems] {
        println(loadedDic)
    }
}


你能发布你的路径吗?也许你的路径不可写,它是/Users/bikram/Library/Developer/CoreSimulator/Devices/3333ED17-BFFB-44B8-BACA-967E5D9A3E38/data/Containers/data/Application/AC822088-C106-4588-9C6E-C6360E0257F3/Documents/Favorites.plistall很好…如果只是写一个字符串,它就很好…我可以看到plist of document directory查看我的更新,你应该让你的'GoogleItems'符合
NSCoding
如果GoogleItems符合NSCoding,则无需强制转换到NSDictionary。你可以发布你的路径吗?也许你的路径不可写,但它是/Users/bikram/Library/Developer/CoreSimulator/Devices/3333ED17-BFFB-44B8-BACA-967E5D9A3E38/data/Containers/data/Application/AC822088-C106-4588-9C6E-C6360E0257F3/Documents/Favorites.plInstall事情很好…如果只是写一个字符串,它就做得很好了…我可以在文档目录的列表中看到更改查看我的更新,你应该让你的'GoogleItems'符合
NSCoding
如果GoogleItems符合NSCoding,则无需强制转换到NSDictionary。你可以发布你的路径吗?也许你的路径不可写,但它是/Users/bikram/Library/Developer/CoreSimulator/Devices/3333ED17-BFFB-44B8-BACA-967E5D9A3E38/data/Containers/data/Application/AC822088-C106-4588-9C6E-C6360E0257F3/Documents/Favorites.plInstall事情很好…如果只是写一个字符串,它就做得很好了…我可以在文档目录的列表中看到更改查看我的更新,你应该让你的'GoogleItems'符合
NSCoding
如果GoogleItems符合NSCoding,则无需强制转换到NSDictionary。你可以发布你的路径吗?也许你的路径不可写,但它是/Users/bikram/Library/Developer/CoreSimulator/Devices/3333ED17-BFFB-44B8-BACA-967E5D9A3E38/data/Containers/data/Application/AC822088-C106-4588-9C6E-C6360E0257F3/Documents/Favorites.plInstall事情很好…如果只是写一个字符串,它就做得很好了…我可以在文档目录的列表中看到更改查看我的更新,如果GoogleItems符合NSCodinglet dictionaryData=NSKeyedArchiver.archivedDataWithRootObject(favoriteGooglelocations),则应该让您的'GoogleItems'符合NSCodinging无需强制转换到NSDictionary…当我尝试使用let dictionaryData=NSKeyedArchiver.archivedDataWithRootObject(favoriteGooglelocations)let result=dictionaryData.writeToFile(路径,原子:true)时,if语句中会出现编译时错误…当未识别的选择器发送到实例0x7fa4d09aee10'时,它会给我错误。请查看我的更新问题。如果dictionaryData.writeToURL(路径,原子性:true){println(true),则需要将类与NSCodinglet dictionaryData=NSKeyedArchiver.archivedDataWithRootObject(favoriteGooglelocations)一致}…..当我尝试使用let dictionaryData=NSKeyedArchiver.archivedDataWithRootObject(favoriteGoog)时,if语句中会出现编译时错误