NSCoding持久化UIImage [英] NSCoding Persisting UIImage

查看:50
本文介绍了NSCoding持久化UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在与本主题相关的stackoverflow上看到了不同的问题.有人说 NSCoding 不符合 UIImage ,而有人说在iOS 5中确实符合.

I have seen different question on stackoverflow related to this topic. Some says that NSCoding does not conform with UIImage and other says that with iOS 5, it does conform.

我想将图像保留在我的应用程序中.我正在使用 encode decode 方法,并且所有内容(标题,标签等)都可以持久保存,但是图像却不能.

I want to persist images in my app. I am using encode and decode methods and everything (title, labels etc) are persisting but NOT the images.

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:title forKey:@"title"];
    [aCoder encodeObject:link forKey:@"link"];
    [aCoder encodeObject:creator forKey:@"creator"];
    [aCoder encodeObject:pubDate forKey:@"pubDate"];
  //  [aCoder encodeObject:thumbnail forKey:@"thumbnail"];
    [aCoder encodeObject:UIImagePNGRepresentation(thumbnail) forKey:@"thumbnail"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        [self setTitle:[aDecoder decodeObjectForKey:@"title"]];
        [self setLink:[aDecoder decodeObjectForKey:@"link"]];
        [self setCreator:[aDecoder decodeObjectForKey:@"creator"]];
        [self setPubDate:[aDecoder decodeObjectForKey:@"pubDate"]];
        [self setThumbnail:[aDecoder decodeObjectForKey:@"thumbnail"]];        
    }
    return self;
}

我还使用了 UIPNGRepresentation ,但是它不起作用.有人可以帮我弄这个吗.

I am also using UIPNGRepresentation but its not working. Can someone help me with this.

谢谢.

推荐答案

您未在编码图像.UIImagePNGRepresentation()返回一个NSData对象.NSData符合NSSecureCoding.我以前没有使用过它,但是文档说您必须像这样解码它:

You're not encoding an image. UIImagePNGRepresentation() returns an NSData object. NSData conforms to NSSecureCoding. I haven't worked with that before, but the docs say that you have to decode it like this:

id obj = [decoder decodeObjectOfClass:[MyClass class] forKey:@"myKey"];

编辑后:上面的内容似乎没有必要.我在测试应用程序中使用了以下代码,并且对图像进行编码和解码的两种方法均有效.

After The above doesn't appear to be necessary. I used the following code in a test app, and both approaches to encoding and decoding an image worked.

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"personName"];
    [aCoder encodeObject:self.image2 forKey:@"thumbnail2"];
    [aCoder encodeObject:UIImagePNGRepresentation(self.image1) forKey:@"thumbnail"];
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self)
    {
        [self setName:[aDecoder decodeObjectForKey:@"personName"]];
        [self setImage2:[aDecoder decodeObjectForKey:@"thumbnail2"]];
        [self setImage1:[UIImage imageWithData:[aDecoder decodeObjectForKey:@"thumbnail"]]];
    }
    return self;
}

正如Aleph所说,问题一定在其他地方.

As Aleph said, the problem must be elsewhere.

这篇关于NSCoding持久化UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆