【问题标题】:Cannot store UIImage in NSMutableDictionary无法将 UIImage 存储在 NSMutableDictionary 中
【发布时间】:2018-06-18 10:46:36
【问题描述】:

我正在从 Parse 服务器获取图像,但是当我收到它并将其存储在 NSMutableDictionary 中时,当我检查它时它无法停留在那里。

NSString* messageSenderId = [receivedMessage objectForKey:@"Sender Id"];
NSLog(@"messageSenderId = %@", messageSenderId);

if([self.avatarDictionary objectForKey:messageSenderId] == nil) { // avatar image for sender not yet stored

PFQuery* userQuery = [PFUser query];
[userQuery whereKey:@"objectId" equalTo:messageSenderId];
PFUser* messageSender = (PFUser *)[[messageSenderQuery findObjects] firstObject];

PFFile *avatarImage = messageSender[@"profilePictureSmall"];
[avatarImage getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) {

        UIImage* storedImage = [UIImage imageWithData:data];
        [self.avatarDictionary setObject:storedImage forKey:messageSender.objectId];
        NSLog(@"objectForKey: %@", [self.avatarDictionary objectForKey:messageSender.objectId]);
        [self.collectionView reloadData];
    }];
}

当我检查 storedImage 变量时,我可以看到它不是空的。但是,NSLog 显示,在我将它存储在里面之后,该键没有对象。

【问题讨论】:

  • 你有没有初始化你的self.avatarDictionary请检查一下,你必须这样做self.avatarDictionary = [NSMutableDictionary dictionary];???

标签: ios objective-c uiimage nsmutabledictionary


【解决方案1】:

当然可以,但我不会。
您的问题可能是由于您没有初始化可变字典。
图片占用大量内存,如果您存储大量图片,您的应用可能会被系统杀死。
更好的方法是在本地保存图像并将它们的路径存储在可变字典中。
或者,如果您仍想将图像存储在 RAM 中,您可以使用NSCache。 NSCache 基本上是一个可变字典,但它通过自动驱逐资源具有更好的内存管理,并且是线程安全的。

【讨论】:

  • 是的。没有初始化,谢谢。我不知道我的应用程序会因为 NSDictionary 中存储的许多图像而被杀死。你知道限制是什么吗?
  • 如果内存占用超过限制,您的应用程序可能会被终止。限制取决于设备,不会写在任何地方。 Apple 建议保持低内存配置。
猜你喜欢
  • 2023-03-17
  • 2011-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-21
相关资源
最近更新 更多