How can I store a UIImage in an NSDictionary?

前端 未结 6 1166
无人及你
无人及你 2021-02-01 20:30

How can I store a UIImage in an NSDictionary?

相关标签:
6条回答
  • 2021-02-01 20:30

    Yes you can:

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:1];
    UIImage *img = ...;
    [dict setObject:img forKey:@"aKeyForYourImage"];
    
    UIImage *imgAgain = [dict objectForKey:@"aKeyForYourImage"];
    
    0 讨论(0)
  • 2021-02-01 20:31

    OK I had this problem recently and the above solutions never worked for me. So if someone else finds their way here to solve the same problem, here is how it's done

    NSDictionary *imageDictionary = @{
     kImageKey:  UIImageJPEGRepresentation(/*INSERT YOUR UIImage HERE*/,0.1)
                                     };
    

    // the 0.1 represents the compression quality 0.0 being lowest to 1.0 being the highest quality

    then to get image back from dictionary use

    [UIImage imageWithData:[imageDictionary objectForKey: kImageKey]];
    
    0 讨论(0)
  • 2021-02-01 20:39

    You cannot store UIImage object in a dictionary. You will have to convert the image into an NSData object and store that in dictionary.

    NSData *imgData = UIImageJPEGRepresentation(yourImage, 0.0f);
    [dictionary setObject:imgData forKey:@"your key"];
    
    0 讨论(0)
  • It depends on what you want to do with your NSDictionary. While, yes, you can store a UIImage in NSDictionary, you may not be able to use said dictionary object in instances where you need it to conform to certain standards.

    For example, you can use an NSDictionary as a value in standardUserDefaults, but only if every object in that dictionary is a property list object. UIImage is not a property list object. NSData is, so you can convert your UIImage to NSData with UIImageJPEGREpresentation, and store it that way, as mentioned above.

    0 讨论(0)
  • 2021-02-01 20:45

    [dictionary setObject:yourImage forKey:@"whatever key you want"];

    Untested ;-)

    0 讨论(0)
  • 2021-02-01 20:49

    [dict setObject:image forKey:@"ImageToStore"];

    0 讨论(0)
提交回复
热议问题