我有一个称为缓存图像的方法。这使用 NSNotification 中心来发布图像已被缓存的信息。我有数据 NSMutableDictionary *userInfo。我正在尝试添加一个观察者来检索图像并使用 _URL 作为键进行保存。问题是 URL 和图像都作为具有自己的键的对象添加到字典中。是否可以检索相应 key 的图像?
- (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 的图像缓存。
最佳答案
您现在拥有此代码:
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];
关于ios - 从 NSMutable Dictionary 获取一个对象并将其设置为新键。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11933515/