IOS學習 --- Swift 對於plist檔案的讀寫
阿新 • • 發佈:2019-01-10
//System Medicine Name
var plistPath = NSBundle.mainBundle().pathForResource("Medicine", ofType: "plist")
var array = NSArray(contentsOfFile: plistPath!)
for temDic in array!{
var dic = temDic as! NSDictionary
var medicineName = dic.objectForKey("name" ) as! String
medicineArray += [medicineName]
}
//Customer Medicine Name
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent("customerMedicine" )
if NSFileManager.defaultManager().fileExistsAtPath(path){
var customerArray = NSArray(contentsOfFile: path)
if let realArray = customerArray{
medicineArray = medicineArray + (realArray as! [(String)])
}
}
if alert.tag == deleteMedicineTag{
//刪除tableView對應的cell
medicineArray.removeAtIndex(deleteMedicineNumber)
//System Medicine Name
var plistPath = NSBundle.mainBundle().pathForResource("Medicine", ofType: "plist")
var array = NSArray(contentsOfFile: plistPath!)!
var customerMedicineIndex = deleteMedicineNumber - array.count
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString//獲取第一個元素
let path = documentsDirectory.stringByAppendingPathComponent("customerMedicine")
var newMedinineArray = NSMutableArray()
if NSFileManager.defaultManager().fileExistsAtPath(path){
var oldArray = NSArray(contentsOfFile: path)
if let realArray = oldArray{
newMedinineArray.addObjectsFromArray(realArray as [AnyObject])
}
}
newMedinineArray.removeObjectAtIndex(customerMedicineIndex)
newMedinineArray.writeToFile(path, atomically: false)
}
if alert.tag == addMedicineAlertTag{
//*********************************
//向plist檔案增加內容
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
let documentsDirectory = paths.objectAtIndex(0) as! NSString
let path = documentsDirectory.stringByAppendingPathComponent("customerMedicine")
//檔案路徑
var newMedinineArray = NSMutableArray()
if NSFileManager.defaultManager().fileExistsAtPath(path){
var oldArray = NSArray(contentsOfFile: path)
if let realArray = oldArray{
newMedinineArray.addObjectsFromArray(realArray as [AnyObject])
}
}
newMedinineArray.addObject(addMedicineAlert.customerTextField.text)//括號內為需要增加的內容
newMedinineArray.writeToFile(path, atomically: false)
medicineArray = [String]()
//***************************************
initMedicineArray()
}
self.tableView.reloadData()