簡體   English   中英

保留圖像陣列的最佳方法?

[英]Best way to persist an array of images?

我正在尋找一種將圖像持久保存到應用程序關閉並重新啟動后可以訪問的數組(或類似數組)的方法-還需要按日期對圖像進行排序。 我目前可以使用以下代碼將圖像存儲到應用程序的NSDocumentDirectory中:

-(NSString *)currentDateandTime
{
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMddyyyy_HHmmss"];
    NSString *dateString = [dateFormat stringFromDate:today];
    return dateString;
}

-(void)saveImageToDocuments
{
    NSData *imageData = UIImagePNGRepresentation(image);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *date = [self currentDateandTime];

    NSString *imagePath =[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_image.png",date]];
}

這意味着我有日期/時間在圖像文件名中的圖像。 將這些圖像存儲在數組或字典中並按日期/時間進行排序的最佳方法是什么。 謝謝閱讀!

我將文件名和日期保存在一個plist文件中,該文件是一系列格式為: @{ @"filename" : imageFileName, @"date": imageDate }的字典。

當將該plist加載到NSArray ,可以通過指定自己的比較方法輕松地按日期對它進行排序。 例如:

NSArray *filenames = [[NSArray alloc] initWithContentsOfFile:filePath];

NSArray *sortedFilenames = [filenames sortedArrayUsingComparator:
    ^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2) 
{
    NSDate *date1 = dict1[@"date"];
    NSDate *date2 = dict2[@"date"];

    return [date1 compare:date2];
}

將圖像數據和日期存儲在某些字典中,然后將這些字典存儲在數組中,然后使用NSKeyedArchiver歸檔數組。

[NSKeyedArchiver archiveRootObject:imageDictionary toFile:@"imagesArray"];

然后,當您要檢索它時:

 NSArray * retrievedImages = [NSKeyedUnarchiver unarchiveObjectWithFile:@"imagesArray"];

然后,只需比較檢索到的數組中各個字典中的日期即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM