Where does the Finder obtain the “date added” of an item in a folder?

China☆狼群 提交于 2020-01-10 04:11:29

问题


If a folder is placed in the Dock you can sort it by "date added" - this is usually the default for the Downloads folder. (Sometimes the Finder does not appear to be using the date added but the date modified, but it can find the date added.) Where is the Finder figuring this out from? The standard file metadata, i.e. as obtained by stat, getattrlist or FSGetCatInfo) does not contain it. TIA


回答1:


Yep, the date added could be inferred from other structures. In fact, it resides in Spotlight metadata.

NSDate *dateAdded(NSURL *url)
{
    NSDate *rslt = nil;
    MDItemRef inspectedRef = nil;

    inspectedRef = MDItemCreateWithURL(kCFAllocatorDefault, (CFURLRef)url);
    if (inspectedRef){
        CFTypeRef cfRslt = MDItemCopyAttribute(inspectedRef, (CFStringRef)@"kMDItemDateAdded");
        if (cfRslt) {
            rslt = (NSDate *)cfRslt;
        }
    }
    return rslt;
}



回答2:


Note: out of date now that Lion’s out.

The Finder isn’t, the Dock is. It tracks this data internally. If you remove a folder and put it back, the “date added” information is lost for existing items.




回答3:


Here's a Swift 5.x version of Wojtek's answer:

public extension URL {
    var dateAdded: Date? {
        if let metadataItemValue = MDItemCreateWithURL(kCFAllocatorDefault, (self as CFURL)) {
            return MDItemCopyAttribute(metadataItemValue, kMDItemDateAdded) as? Date
        }
        return nil
    }
}

I've tested this back to Swift 4.x, and I think it'll compile without modification back to Swift 3.x if you need that too. Just be aware that, before Swift 5, its inferred visibility would be internal rather than public.



来源:https://stackoverflow.com/questions/6007186/where-does-the-finder-obtain-the-date-added-of-an-item-in-a-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!