2015-06-05 4 views
0

я есть словарь типа, как показано нижеКак добавить словарь в Plist в SWIFT

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.writeToFile(path, atomically: true)

Ошибка:> [Int: GoogleItems ] не имеет члена с именем writeToFile

ОБНОВЛЕНО: Путь я пишу это

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

let documentDirectory = paths[0] as! String 

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

Как я могу добавить словарь в Plist, Есть другой способ сделать это?

+0

Привет, я обновить код я проверить, Вы можете обратиться к нему – Leo

ответ

1

Вы должны преобразовать словарь в NSDictionary, так что вы можете использовать writeToFile

Попробуйте бросить эту

let succeed = (favoriteGooglelocations as NSDictionary).writeToFile(path, atomically: true) 

Если удастся ложно, проверьте класс 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) 
     } 

    } 
+0

спасибо. но это не получилось ... дайте мне ложный результат –

+0

Можете ли вы опубликовать свой путь? Возможно, ваш путь не может быть записан – Leo

+0

вот он/Пользователи/bikram/Library/Developer/CoreSimulator/Devices/3333ED17-BFFB-44B8- BACA-967E5D9A3E38/данные/Контейнеры/данные/Применение/AC822088-C106-4588-9C6E-C6360E0257F3/Документы/Избранное.plist –

1

обновление: 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) 
    } 
} 
+0

let dictionaryData = NSKeyedArchiver.archivedDataWithRootObject (favoriteGooglelocations) if dictionaryData .writeToURL (путь, атомарно: истинно) { Println (истина) } ..... в то время как я стараюсь это дает мне компиляции ошибки времени, если оператор –

+0

, когда я пытался, как позволяют dictionaryData = NSKeyedArchiver.archivedDataWithRootObject (favoriteGooglelocations) let result = dictionaryData.writeToFile (путь, атомарно: истина) ... он дает мне ошибку, поскольку nrecognized selector отправляется в экземпляр 0x7fa4d09aee10 ', пожалуйста, см. мой обновленный вопрос –

+0

Вам нужно соответствовать классу NSCoding –

Смежные вопросы