更新:我最初錯誤地認爲,唯一的選擇是使用一個的CoreFoundation(C API)的方法,但實際上並不是真正的(thanks):在基金會(ObjC API)NSURL
類並提供一種方法來檢測搜索別名:
// OSX 10.9+
// Indicates if the specified filesystem path is a Finder alias.
// Returns an optional Boolean: if the lookup failed, such when the path doesn't exist,
// nil is returned.
// Example: isFinderAlias("/path/to/an/alias")
func isFinderAlias(path:String) -> Bool? {
let aliasUrl = NSURL(fileURLWithPath: path)
var isAlias:AnyObject? = nil
do {
try aliasUrl.getResourceValue(&isAlias, forKey: NSURLIsAliasFileKey)
} catch _ {}
return isAlias as! Bool?
}
[不推薦,除了作爲練習使用UnsafeMutablePointer<Void>
]
下面介紹如何使用基於C-的CoreFoundation API做到這一點:
IsAliasFile()
在OS X 10.4中已停用,
- 由
FSIsAliasFile()
,這是在10.8棄用成功。
- 目前的方法是使用
CFURLCopyResourcePropertyForKey()
,這在Swift中不太好玩,因爲必須使用手動內存管理和UnsafeMutablePointer<Void>
。
我希望我有足夠的內存管理權:
import Foundation
// Indicates if the specified filesystem path is a Finder alias.
// Returns an optional Boolean: if the lookup failed, such when the path
// doesn't exist, nil is returned.
// Example: isFinderAlias("/path/to/an/alias")
func isFinderAlias(path:String) -> Bool? {
var isAlias:Bool? = nil // Initialize result var.
// Create a CFURL instance for the given filesystem path.
// This should never fail, because the existence isn't verified at this point.
// Note: No need to call CFRelease(fUrl) later, because Swift auto-memory-manages CoreFoundation objects.
let fUrl = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, false)
// Allocate void pointer - no need for initialization,
// it will be assigned to by CFURLCopyResourcePropertyForKey() below.
let ptrPropVal = UnsafeMutablePointer<Void>.alloc(1)
// Call the CoreFoundation function that copies the desired information as
// a CFBoolean to newly allocated memory that prt will point to on return.
if CFURLCopyResourcePropertyForKey(fUrl, kCFURLIsAliasFileKey, ptrPropVal, nil) {
// Extract the Bool value from the memory allocated.
isAlias = UnsafePointer<CFBoolean>(ptrPropVal).memory as Bool
// Since the CF*() call contains the word "Copy", WE are responsible
// for destroying (freeing) the memory.
ptrPropVal.destroy()
}
// Deallocate the pointer
ptrPropVal.dealloc(1)
return isAlias
}
你是對的。它正在工作,但我會改變這一點。問題仍然是別名 – Silve2611