我有一个名为缓存图像的方法。这使用NSNotification中心发布图像已缓存的信息。我有数据NSMutableDictionary * userInfo。我正在尝试添加一个观察者来检索图像并使用_URL作为关键字进行保存。问题是URL和图像都作为具有自己的键的对象添加到字典中。是否可以检索相应密钥的图像?
- (void)cacheImage:(UIImage *)image
{
if (!_cancelled)
{
if (image && _URL)
{
BOOL storeInCache = YES;
if ([_URL isFileURL])
{
if ([[[_URL absoluteURL] path] hasPrefix:[[NSBundle mainBundle] resourcePath]])
{
//do not store in cache
storeInCache = NO;
}
}
if (storeInCache)
{
[_cache setObject:image forKey:_URL];
}
}
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
image, AsyncImageImageKey,
_URL, AsyncImageURLKey,
nil];
NSLog(@"%@",_URL);
if (_cache)
{
[userInfo setObject:_cache forKey:AsyncImageCacheKey];
}
_loading = NO;
[[NSNotificationCenter defaultCenter] postNotificationName:AsyncImageLoadDidFinish
object:_target
userInfo:[[userInfo copy] autorelease]];
}
else
{
_loading = NO;
_cancelled = NO;
}
}
在我的其他类viewcontroller.m文件
中 -(void)ViewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(imageLoaded:)
name:AsyncImageLoadDidFinish
object:nil];
}
- (void)imageLoaded:(NSNotification *)notification
{
NSMutableDictionary *imageCache = notification.object;// help needed here
}
我试图添加一个观察者,但我无法想象如何使用对象'_URL'作为图像的关键。使用观察者接收对象后,我必须找到该URL的图像缓存。
答案 0 :(得分:1)
您现在拥有此代码:
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
image, AsyncImageImageKey,
_URL, AsyncImageURLKey,
nil];
所以当你想将它添加到imageCache:
时NSURL *_url = [userInfo objectForKey:AsyncImageURLKey];
UIImage *image = [userInfo objectForKey:AsyncImageImageKey];
[imageCache setObject:image forKey:_url];