更新:我最初错误地认为唯一的选择是使用 CoreFoundation (C API) 方法,但事实并非如此 (thanks): Foundation (ObjC API) 类 NSURL 确实提供了一种检测 Finder 别名的方法:
// 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
}