首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Cocoa中将自定义对象写入.plist

在Cocoa中,将自定义对象写入.plist文件需要遵循以下步骤:

  1. 创建一个自定义对象,该对象需要遵循NSCoding协议,以便可以将其序列化为数据并将其写入.plist文件。
代码语言:swift
复制
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")
    }
}
  1. 创建一个.plist文件,并将其添加到项目中。
  2. 将自定义对象写入.plist文件。
代码语言:swift
复制
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)
}
  1. 从.plist文件中读取自定义对象。
代码语言:swift
复制
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代码。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券