【发布时间】:2013-10-23 05:28:29
【问题描述】:
我正在我正在开发的应用程序中构建图像缓存,其中缓存是 NSMutableDictionary。
字典最初是这样的:
NSMutableDictionary *imageCacheDictionary = [NSMutableDictionary initWithContentsOfURL:imageCacheURL];
//alloc-init imageCacheDictionary if nil
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *imageURLAsString = [imageURL absoluteString];
[imageCacheDictionary setObject:imageData forKey:imageURLAsString];
if ([imageCacheDictionary writeToURL:cacheURL atomically:YES]) {
NSLog(@"file written");
} else {
NSLog(@"file NOT written");
}
效果很好。
然后当我决定添加代码以将缓存保持在一定大小以下时,我尝试添加一个标签,以便我可以先删除最旧的照片。
NSMutableDictionary *imageCacheDictionary = [NSMutableDictionary initWithContentsOfURL:imageCacheURL];
//alloc-init imageCacheDictionary if nil
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *imageURLAsString = [imageURL absoluteString];
NSDate *currentTime = [NSDate date];
NSDictionary *imageDataWithTime = @{currentTime : imageDataWithTime};
[imageCacheDictionary setObject:imageDataWithTime forKey:imageURLAsString];
if ([imageCacheDictionary writeToURL:cacheURL atomically:YES]) {
NSLog(@"file written");
} else {
NSLog(@"file NOT written");
}
这不起作用。
据我所知,NSDate 符合属性列表,因此 writeToURL 应该允许您写入磁盘,但不是。
然后我尝试使用 NSKeyedArchiver 将其转换为 NSData。
...
NSData *currentTimeAsData = [NSKeyedArchiver archivedDataWithRootObject:[NSDate date]];
NSDictionary *imageDataWithTime = @{currentTimeAsData : imageData};
...
还是不行。
但是如果我将 NSDate 对象转换为 NSString 或者只是用 NSString 替换它,它就可以正常工作。
...
NSString *currentTime = [[NSDate date] description];
NSDictionary *imageDataWithTime = @{currentTime : imageData};
...
或者:
...
NSString *currentTime = @"Hey! Now is now!";
NSDictionary *imageDateWithTime = @{currentTime : imageData};
...
所以....为什么?如果 NSDate 和 NSData 都符合属性列表,为什么它们都没有写入嵌套字典中的磁盘,而 NSString 写入正常?
【问题讨论】:
-
能否请您也粘贴 imageURl?
-
此链接可能对您有所帮助stackoverflow.com/questions/5361630/…
-
imageURL 是 VC 设置的一个属性,它创建了这个 VC 的 segue,所以在我的实际代码中它是 self.imageURL。
标签: ios objective-c nsdate nsdata