2014-07-11 24 views
5

Tôi có một tập tin mẫu plist, favCities.plist. Đây là mã mẫu của tôi:Viết vào tập tin plist trong Swift

override func viewDidLoad() { 
    super.viewDidLoad() 


    let path = NSBundle.mainBundle().pathForResource("favCities", ofType: "plist") 
    var plistArray = NSArray(contentsOfFile: path) as [Dictionary<String, String>] 

    var addDic: Dictionary = ["ZMV": "TEST", "Name": "TEST", "Country": "TEST"] 
    plistArray += addDic 
    (plistArray as NSArray).writeToFile(path, atomically: true) 

    var plistArray2 = NSArray(contentsOfFile: path) 

    for tempDict1 in plistArray2 { 
     var tempDict2: NSDictionary = tempDict1 as NSDictionary 
     var cityName: String = tempDict2.valueForKey("Name") as String 
     var cityZMV: String = tempDict2.valueForKey("ZMV") as String 
     var cityCountry: String = tempDict2.valueForKey("Country") as String 
     println("City: \(cityName), ZMV: \(cityZMV), Country: \(cityCountry)") 
    } 

Thoạt nhìn, mọi thứ hoạt động tốt. Đầu ra trông như sau:

City: Moscow, ZMV: 00000.1.27612, Country: RU 
City: New York, ZMV: 10001.5.99999, Country: US 
City: TEST, ZMV: TEST, Country: TEST 

Nhưng khi tôi ngắt ứng dụng, tôi thấy rằng tệp favCities.plist của tôi không thay đổi. Vẫn còn hai giá trị. Các giá trị này - City: TEST, ZMV: TEST, Country: TEST - không được thêm vào. Nếu tôi khởi động lại ứng dụng, sau đó một lần nữa tôi thấy 3 dòng đầu ra, mặc dù phải có 4.

Điều gì là sai?

CẬP NHẬT:

tôi đã thay đổi mã này:

override func viewDidLoad() { 
    super.viewDidLoad() 

    let fileManager = (NSFileManager.defaultManager()) 
    let directorys : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String] 

    if (directorys! != nil){ 
     let directories:[String] = directorys!; 
     let dictionary = directories[0]; 

     let plistfile = "favCities.plist" 
     let plistpath = dictionary.stringByAppendingPathComponent(plistfile); 

     println("\(plistpath)") 

     var plistArray = NSArray(contentsOfFile: plistpath) as [Dictionary<String, String>] 

     var addDic: Dictionary = ["ZMV": "TEST", "Name": "TEST", "Country": "TEST"] 
     plistArray += addDic 

     (plistArray as NSArray).writeToFile(plistpath, atomically: false) 

     var plistArray2 = NSArray(contentsOfFile: plistpath) 

     for tempDict1 in plistArray2 { 
      var tempDict2: NSDictionary = tempDict1 as NSDictionary 
      var cityName: String = tempDict2.valueForKey("Name") as String 
      var cityZMV: String = tempDict2.valueForKey("ZMV") as String 
      var cityCountry: String = tempDict2.valueForKey("Country") as String 
      println("City: \(cityName), ZMV: \(cityZMV), Country: \(cityCountry)") 
     } 
    } 
    else { 
     println("ERROR!") 
    } 

} 

Bây giờ khi bạn chạy các ứng dụng số lượng hàng trong tăng sản lượng:

City: Moscow, ZMV: 00000.1.27612, Country: RU 
City: New York, ZMV: 10001.5.99999, Country: US 
City: TEST, ZMV: TEST, Country: TEST 
City: TEST, ZMV: TEST, Country: TEST 
........ 

NHƯNG! Nếu xem tập tin favCities.plist, nằm trong thư mục dự án (Project Navigator in Xcode), nó vẫn không thay đổi - có hai dòng!

Nếu đi bộ dọc theo con đường, được lưu trữ trong biến plistpath-/Users/admin/Library/Developer/CoreSimulator/Devices/55FD9B7F-78F6-47E2-9874-AF30A21CD4A6/data/Containers/Data/Application/DEE6C3C8-6A44-4255-9A87-2CEF6082A63A/Documents/

Sau đó, có một tập tin favCities.plist hơn. Nó chứa tất cả các thay đổi tạo ra ứng dụng. Tôi đang làm gì sai? Làm thế nào tôi có thể thấy tất cả các thay đổi trong một tập tin nằm trong thư mục dự án (Project Navigator)?

+2

giá trị kiểm tra trở lại của 'writeToFile', và bạn sẽ thấy nó thất bại. vì các tệp trong gói chính chỉ đọc được –

+1

có thể trùng lặp của [viết NSDictionary thành plist trong gói ứng dụng của tôi] (http://stackoverflow.com/questions/2502193/writing-nsdictionary-to-plist-in-my-app-bundle) –

+2

(Vì vậy, tất cả các lỗi điển hình trong các ứng dụng iOS đã từng được sử dụng Objective-C, bây giờ được tạo lại bằng Swift :-) –

Trả lời

0

Vâng, đây giải quyết vấn đề - Swift - Read plist

Nhưng plist-tập tin trong thư mục dự án chỉ sử dụng cho tình hình bất động sản giống như .....

0

Nếu bạn nhìn lại nhanh như thế nào hoặc plist viết trên chìa khóa đã tồn tại trong plist

var path = NSBundle.mainBundle().pathForResource("GameParam", ofType: "plist") 
    if var dict = NSMutableDictionary(contentsOfFile: path!) { 
     ToolKit.log(dict) 
     dict.setValue("blablabla", forKey: "keyInPlist") 

     dict.writeToFile(path!, atomically: false) 
    } 
0

Hầu hết, mọi người muốn lưu trữ một danh sách một cái gì đó, vì vậy đây là chia sẻ của tôi về cách để làm điều này, cũng có, ở đây tôi không sao chép các tập tin plist, tôi chỉ tạo ra nó . Tiết kiệm thực tế/tải là khá giống với câu trả lời từ Rebeloper

xcode 7 beta, Swift 2,0

tiết kiệm

func SaveItemFavorites(items : Array<ItemFavorite>) -> Bool 
{ 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
    let docuDir = paths.firstObject as! String 
    let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath) 
    let filemanager = NSFileManager.defaultManager() 

    let array = NSMutableArray()   

    for var i = 0 ; i < items.count ; i++ 
    { 
     let dict = NSMutableDictionary() 
     let ItemCode = items[i].ItemCode as NSString 

     dict.setObject(ItemCode, forKey: "ItemCode") 
     //add any aditional.. 
     array[i] = dict 
    } 

    let favoritesDictionary = NSDictionary(object: array, forKey: "favorites") 
    //check if file exists 
    if(!filemanager.fileExistsAtPath(path)) 
    { 
     let created = filemanager.createFileAtPath(path, contents: nil, attributes: nil) 
     if(created) 
     { 
      let succeeded = favoritesDictionary.writeToFile(path, atomically: true) 
      return succeeded 
     } 
     return false 
    } 
    else 
    { 
     let succeeded = notificationDictionary.writeToFile(path, atomically: true) 
     return succeeded 
    } 
} 

ít lưu ý từ các tài liệu:

NSDictionary.writeToFile (đường dẫn: nguyên tử :)

Phương pháp này một cách đệ quy xác nhận rằng tất cả các đối tượng chứa là những đối tượng danh sách tài sản (trường hợp của NSData, NSDate, NSNumber, NSString, NSArray, hoặc NSDictionary) trước khi viết ra các tập tin, và trả về NO nếu tất cả các đối tượng không phải là đối tượng danh sách thuộc tính, vì tệp kết quả sẽ không phải là danh sách thuộc tính hợp lệ.

Vì vậy, bất cứ điều gì bạn đặt ở dict.SetObject() phải là một trong các loại được đề cập ở trên.

tải

private let ItemFavoritesFilePath = "ItemFavorites.plist" 

func LoadItemFavorites() -> Array<ItemFavorite> 
{ 
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray 
    let docuDir = paths.firstObject as! String 
    let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath) 
    let dict = NSDictionary(contentsOfFile: path) 
    let dictitems : AnyObject? = dict?.objectForKey("favorites") 

    var favoriteItemsList = Array<ItemFavorite>() 

    if let arrayitems = dictitems as? NSArray 
    { 
     for var i = 0;i<arrayitems.count;i++ 
     { 
      if let itemDict = arrayitems[i] as? NSDictionary 
      { 
       let ItemCode = itemDict.objectForKey("ItemCode") as? String 
       //get any additional 

       let ItemFavorite = ItemFavorite(item: ItemCode) 
       favoriteItemsList.append(ItemFavorite) 
      } 
     } 
    } 

    return favoriteItemsList 
}