从 NSMutable 字典中获取对象并将其设置为新键



我有一个叫做缓存图像的方法。这使用 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;
    }
 }

在我的其他类视图中控制器.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];

因此,当您要将其添加到图像缓存中时:

NSURL *_url = [userInfo objectForKey:AsyncImageURLKey];
UIImage *image = [userInfo objectForKey:AsyncImageImageKey];
[imageCache setObject:image forKey:_url];

最新更新