2015-04-20 41 views
1

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應該可以上的每個文件在磁盤上。

+0

這裏所涉及的沙盒? – stevesliva

+0

我不這麼認爲:我根本不使用沙盒。除非這是一個MAS專用功能,但我不這麼認爲。 – duhanebel

回答

0

顯然,優勝美地只有在知道某物正試圖追蹤其身份(如版本或iCloud)時,纔會將DocumentIdentifier分配給文件。

我沒有看到任何方式與內核交談,並告訴它開始跟蹤你感興趣的文件。我希望在未來的版本中有所改變,因爲API已經在OS X 10.10上公開,而且在這一點上它幾乎是無用的。

1

我在這個問題上提出了一個蘋果的錯誤,並得到了我的報告的反饋。截至目前,有關跟蹤DocumentIdentifier的信息尚未成爲文檔的一部分,但票證仍處於開放狀態。

缺少的信息是,默認情況下文件系統不跟蹤DocumentIdentifier。您必須通過在chflagsUF_TRACKED標誌位上使用chflags設置每個要跟蹤的文件上的標誌來啓用跟蹤。

下面的腳本將打印DocumentIdentifier一個文件:

https://gist.github.com/cmittendorf/fac92272a941a9cc64d5

而且這個腳本將使跟蹤DocumentIdentifier

https://gist.github.com/cmittendorf/b680d1a03aefa08583d7

+0

我想知道如果在很多文件上啓用這個功能會對性能產生什麼影響。 – duhanebel

+0

非常有趣。我也想知道會對性能產生什麼影響。而且,如果它可以在網絡文件系統上工作。 –