Reputation: 646
Im trying to read a plist that contains an Array of Ints . This is my first time using them , and i can read them in fine , but the plist doesn't update when i write to it.
here's my code for the reading and writing..
class FavouritesManager {
var myArray:NSMutableArray = [0]
func loadDataPlist(){
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0)as NSString
let path = documentsDirectory.stringByAppendingPathComponent("FavouriteIndex.plist")
let fileManager = NSFileManager.defaultManager()
if(!fileManager.fileExistsAtPath(path))
{
let bundle = NSBundle.mainBundle().pathForResource("FavouriteIndex", ofType: "plist")
fileManager.copyItemAtPath(bundle!, toPath: path, error:nil)
}
myArray = NSMutableArray(contentsOfFile: path)!
println(myArray)
}
func writeToPlist(indexValue:Int) {
if let path = NSBundle.mainBundle().pathForResource("FavouriteIndex", ofType: "plist"){
myArray.addObject(indexValue)
myArray.addObject(indexValue+5)
myArray.addObject(indexValue+10)
myArray.addObject(indexValue+15)
myArray.writeToFile(path, atomically: true)
}
}
The purpose of this code is to store the index of the tableViewCell that has been favourited so that I can display that row in my favourite tableViewControllwe
BTW - my plist looks like this...
Thanks !
Upvotes: 2
Views: 8046
Reputation: 3146
Your problem is that you are loading the plist into your documents directory in loadDataPlist()
, but you are still pulling the plist from it's original location in your writeToPlist(indexValue:)
function. So you are trying to write to a plist at a readonly location. Change your write function to this:
func writeToPlist(indexValue:Int) {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("MyPlist.plist")
if var plistArray = NSMutableArray(contentsOfFile: path) {
plistArray.addObject(indexValue)
plistArray.addObject(indexValue+5)
plistArray.addObject(indexValue+10)
plistArray.addObject(indexValue+15)
plistArray.writeToFile(path, atomically: false)
}
}
Note that instead of adding the values to myArray
I'm only writing to the plist. You'll have to decide if you want to maintain the two arrays (the local variable myArray
and the array in the plist) depending on what you're using this for. Either way, this should fix your problem.
Upvotes: 4