OSX Yosemite在NSURL上引入了一个非常方便的属性:NSURLDocumentIdentifierKey
。为什么NSURL的NSURLDocumentIdentifierKey(几乎)总是零?
从文档报价:
NSURLDocumentIdentifierKey
The document identifier returned as an NSNumber (read-only). The document identifier is a value assigned by the kernel to a file or directory. This value is used to identify the document regardless of where it is moved on a volume. The identifier persists across system restarts. It is not transferred when the file is copied, but it survives "safe save” operations. For example, it remains on the path to which it was assigned, even after calling the replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: method. Document identifiers are only unique within a single volume. This property is not supported by all volumes.
Available in OS X v10.10 and iOS 8.0.
不幸的是,价值似乎主要零(除了看起来完全断开一个到另一个罕见的例子)。
特别是,该代码会抛出异常,在最后一行(在优胜美地10.10.3测试):
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *attributesFlags = @[NSURLNameKey, mNSURLDocumentIdentifierKey];
NSDirectoryEnumerator *en = [fileManager enumeratorAtURL:[NSURL URLWithString:NSHomeDirectory()]
includingPropertiesForKeys:attributesFlags
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error) {
NSAssert(NO, @"An error has occured");
return YES;
}];
for(NSURL *URL in en) {
NSNumber *documentID = nil;
NSError *error = nil;
BOOL result = [URL getResourceValue:&documentID forKey:NSURLDocumentIdentifierKey error:&error]; \
NSAssert(result == YES && error==nil, @"Unable to read property. Error: %@", error); \
NSLog(@"Processing file: %@", URL);
// This will break most of the times
NSAssert(documentID != nil, @"Document ID should not be nil!!");
}
也许我误解的文件,但在我看来NSURLDocumentIdentifierKey
应该可以上的每个文件在磁盘上。
这里所涉及的沙盒? – stevesliva
我不这么认为:我根本不使用沙盒。除非这是一个MAS专用功能,但我不这么认为。 – duhanebel