在Cocoa中,将自定义对象写入.plist文件需要遵循以下步骤:
import Foundation
class CustomObject: NSObject, NSCoding {
var property1: String
var property2: Int
init(property1: String, property2: Int) {
self.property1 = property1
self.property2 = property2
}
required init?(coder aDecoder: NSCoder) {
self.property1 = aDecoder.decodeObject(forKey: "property1") as? String ?? ""
self.property2 = aDecoder.decodeInteger(forKey: "property2")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(property1, forKey: "property1")
aCoder.encode(property2, forKey: "property2")
}
}
func writeCustomObjectToPlist(customObject: CustomObject, plistName: String) {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let path = documentsDirectory + "/\(plistName)"
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
let bundle = Bundle.main
let plistPath = bundle.path(forResource: plistName, ofType: "plist")!
try! fileManager.copyItem(atPath: plistPath, toPath: path)
}
let data = NSMutableData(contentsOfFile: path)!
let archiver = NSKeyedArchiver(forWritingWith: data)
archiver.encode(customObject, forKey: "customObject")
archiver.finishEncoding()
data.write(toFile: path, atomically: true)
}
func readCustomObjectFromPlist(plistName: String) -> CustomObject? {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let path = documentsDirectory + "/\(plistName)"
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: path) {
return nil
}
let data = NSData(contentsOfFile: path)!
let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data)
let customObject = unarchiver.decodeObject(forKey: "customObject") as? CustomObject
unarchiver.finishDecoding()
return customObject
}
这样,您就可以将自定义对象写入.plist文件并从中读取它们了。请注意,这些示例使用Swift编写,但您可以根据需要将其转换为Objective-C代码。
领取专属 10元无门槛券
手把手带您无忧上云