문제

특정 순서로 폴더의 내용을 가져 오는 방법이 있습니까? 날짜 수정으로 주문한 파일 속성 사전 (또는 파일 이름) 배열을 원합니다.

지금, 나는 이런 식으로하고있다 :

  • 파일 이름으로 배열을 가져옵니다
  • 각 파일의 속성을 가져옵니다
  • 파일의 경로와 수정 날짜를 사전에 날짜로 저장하십시오.

다음으로 사전을 날짜 순서대로 출력해야하지만 더 쉬운 방법이 있는지 궁금했습니다. 그렇지 않다면, 나에게 이것을 할 수있는 코드 스 니펫이 있습니까?

감사.

도움이 되었습니까?

해결책

위의 Nall의 코드는 올바른 방향으로 나를 지적했지만 위에 게시 된 코드에 실수가 있다고 생각합니다. 예를 들어:

  1. filesAndProperties 사용을 할당했습니다 NMutableDictonary 대신 NSMutableArray?

  2. 
    NSDictionary* properties = [[NSFileManager defaultManager]
                                            attributesOfItemAtPath:NSFileModificationDate
                                            error:&error];
    
    
    위의 코드는 잘못된 매개 변수를 전달합니다 attributesOfItemAtPath - 그것은해야한다 attributesOfItemAtPath:path

  3. 당신은 정렬하고 있습니다 files 배열이지만 정렬해야합니다 filesAndProperties.


수정과 함께 동일하게 구현하고 블록을 사용하고 아래에 게시했습니다.


    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsPath = [searchPaths objectAtIndex: 0]; 

    NSError* error = nil;
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
    if(error != nil) {
        NSLog(@"Error in reading files: %@", [error localizedDescription]);
        return;
    }

    // sort by creation date
    NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];
    for(NSString* file in filesArray) {
        NSString* filePath = [iMgr.documentsPath stringByAppendingPathComponent:file];
        NSDictionary* properties = [[NSFileManager defaultManager]
                                    attributesOfItemAtPath:filePath
                                    error:&error];
        NSDate* modDate = [properties objectForKey:NSFileModificationDate];

        if(error == nil)
        {
            [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                           file, @"path",
                                           modDate, @"lastModDate",
                                           nil]];                 
        }
    }

        // sort using a block
        // order inverted as we want latest date first
    NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
                            ^(id path1, id path2)
                            {                               
                                // compare 
                                NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:
                                                           [path2 objectForKey:@"lastModDate"]];
                                // invert ordering
                                if (comp == NSOrderedDescending) {
                                    comp = NSOrderedAscending;
                                }
                                else if(comp == NSOrderedAscending){
                                    comp = NSOrderedDescending;
                                }
                                return comp;                                
                            }];

다른 팁

이건 어때:

// Application documents directory
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:documentsURL
                                                          includingPropertiesForKeys:@[NSURLContentModificationDateKey]
                                                                             options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                               error:nil];

NSArray *sortedContent = [directoryContent sortedArrayUsingComparator:
                        ^(NSURL *file1, NSURL *file2)
                        {
                            // compare
                            NSDate *file1Date;
                            [file1 getResourceValue:&file1Date forKey:NSURLContentModificationDateKey error:nil];

                            NSDate *file2Date;
                            [file2 getResourceValue:&file2Date forKey:NSURLContentModificationDateKey error:nil];

                            // Ascending:
                            return [file1Date compare: file2Date];
                            // Descending:
                            //return [file2Date compare: file1Date];
                        }];

더 간단한 ...

NSArray*  filelist_sorted;
filelist_sorted = [filelist_raw sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDictionary* first_properties  = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj1] error:nil];
    NSDate*       first             = [first_properties  objectForKey:NSFileModificationDate];
    NSDictionary* second_properties = [[NSFileManager defaultManager] attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", path_thumb, obj2] error:nil];
    NSDate*       second            = [second_properties objectForKey:NSFileModificationDate];
    return [second compare:first];
}];

너무 느립니다

[[NSFileManager defaultManager]
                                attributesOfItemAtPath:NSFileModificationDate
                                error:&error];

이 코드를 시도하십시오 :

+ (NSDate*) getModificationDateForFileAtPath:(NSString*)path {
    struct tm* date; // create a time structure
    struct stat attrib; // create a file attribute structure

    stat([path UTF8String], &attrib);   // get the attributes of afile.txt

    date = gmtime(&(attrib.st_mtime));  // Get the last modified time and put it into the time structure

    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setSecond:   date->tm_sec];
    [comps setMinute:   date->tm_min];
    [comps setHour:     date->tm_hour];
    [comps setDay:      date->tm_mday];
    [comps setMonth:    date->tm_mon + 1];
    [comps setYear:     date->tm_year + 1900];

    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDate *modificationDate = [[cal dateFromComponents:comps] addTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT]];

    [comps release];

    return modificationDate;
}

코드는 컴파일 오류로 가득 찬 iPhone SDK에서 작동하지 않습니다. 업데이트 된 코드를 찾으십시오

NSInteger lastModifiedSort(id path1, id path2, void* context)
{
    int comp = [[path1 objectForKey:@"lastModDate"] compare:
     [path2 objectForKey:@"lastModDate"]];
    return comp;
}

-(NSArray *)filesByModDate:(NSString*) path{

    NSError* error = nil;

    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path
                                                                         error:&error];
    if(error == nil)
    {
        NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];

        for(NSString* imgName in filesArray)
        {

            NSString *imgPath = [NSString stringWithFormat:@"%@/%@",path,imgName];
            NSDictionary* properties = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:imgPath
                                        error:&error];

            NSDate* modDate = [properties objectForKey:NSFileModificationDate];

            if(error == nil)
            {
                [filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                               imgName, @"path",
                                               modDate, @"lastModDate",
                                               nil]];                     
            }else{
                NSLog(@"%@",[error description]);
            }
        }
        NSArray* sortedFiles = [filesAndProperties sortedArrayUsingFunction:&lastModifiedSort context:nil];

        NSLog(@"sortedFiles: %@", sortedFiles);      
        return sortedFiles;
    }
    else
    {
        NSLog(@"Encountered error while accessing contents of %@: %@", path, error);
    }

    return filesArray;
}

`

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top