代码之家  ›  专栏  ›  技术社区  ›  Alex

Swift将一些字符串值设置为文件的属性

  •  2
  • Alex  · 技术社区  · 8 年前

    根据苹果的文件,我们可以为一个文件设置很多属性

    我想为文件设置一个额外的参数。参数是一个字符串,我找不到任何可以设置字符串的属性。 例如,我试过

    try FileManager.default.setAttributes([FileAttributeKey.ownerAccountName: NSString(string: "0B2TwsHM7lBpSMU1tNXVfSEp0RGs"), FileAttributeKey.creationDate: date], ofItemAtPath: filePath.path)
    

    let keys = try FileManager.default.attributesOfItem(atPath: filePath.path)
    print(keys)
    

    我只得到。creationDate已更改

    [__C.FileAttributeKey(_rawValue: NSFileType): NSFileTypeRegular,
    __C.FileAttributeKey(_rawValue: NSFilePosixPermissions): 420,
    __C.FileAttributeKey(_rawValue: NSFileSystemNumber): 16777220,
    __C.FileAttributeKey(_rawValue: NSFileReferenceCount): 1,
    __C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountName): staff,
    __C.FileAttributeKey(_rawValue: NSFileSystemFileNumber): 8423614,
    __C.FileAttributeKey(_rawValue: NSFileGroupOwnerAccountID): 20,
    __C.FileAttributeKey(_rawValue: NSFileModificationDate): 2017-08-16 06:03:57 +0000, 
    __C.FileAttributeKey(_rawValue: NSFileCreationDate): 1970-01-01 00:33:20 +0000, 
    __C.FileAttributeKey(_rawValue: NSFileSize): 9795,
    __C.FileAttributeKey(_rawValue: NSFileExtensionHidden): 0,
    __C.FileAttributeKey(_rawValue: NSFileOwnerAccountID): 501]
    

    1 回复  |  直到 8 年前
        1
  •  3
  •   Michael Dautermann    8 年前

    文档中说“您可以设置以下属性”。这意味着您只能通过这些API设置这些特定属性。

    你真正想要的是 Extended Attributes ,它们使用一组单独的(C风格)API。

    let directory = NSTemporaryDirectory()
    let someExampleText = "some sample text goes here"
    do {
        try someExampleText.write(toFile: "\(directory)/test.txt", atomically: true, encoding: .utf8)
    } catch let error {
        print("error while writing is \(error.localizedDescription)")
    }
    let valueString = "setting some value here"
    let result = setxattr("\(directory)/test.txt", "com.stackoverflow.test", valueString, valueString.characters.count, 0, 0)
    
    print("result is \(result) ; errno is \(errno)")
    if errno != 0
    {
        perror("could not save")
    }
    
    let sizeOfRetrievedValue = getxattr("\(directory)/test.txt", "com.stackoverflow.test", nil, 0, 0, 0)
    
    var data = Data(count: sizeOfRetrievedValue)
    
    let newResult = data.withUnsafeMutableBytes({
        getxattr("\(directory)/test.txt", "com.stackoverflow.test", $0, data.count, 0, 0)
    })
    
    if let resultString = String(data: data, encoding: .utf8)
    {
        print("retrieved string is \(resultString)")
    }