1

我在与此主题相关的 stackoverflow 上看到了不同的问题。有人说不NSCoding符合,有人说符合UIImageiOS 5。

我想在我的应用程序中保留图像。我正在使用encodedecode方法,一切(标题、标签等)都在持续,但图像却没有。

- (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,但它不起作用。有人可以帮我弄这个吗。

谢谢。

4

2 回答 2

7

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

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

编辑后:以上似乎没有必要。我在测试应用程序中使用了以下代码,两种编码和解码图像的方法都有效。

- (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 所说,问题一定出在其他地方。

于 2013-01-14T06:32:44.903 回答
2

尝试这个:


- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:title forKey:@"title"];
    [aCoder encodeObject:link forKey:@"link"];
    [aCoder encodeObject:creator forKey:@"creator"];
    [aCoder encodeObject:pubDate forKey:@"pubDate"];
    NSData* data = UIImagePNGRepresentation(thumbnail);
    NSLog(@"Data length: %d", data.length);
    [aCoder encodeObject:data 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"]];
        NSData* data = [aDecoder decodeObjectForKey:@"thumbnail"];
        NSLog(@"Data length: %d", data.length);
        [self setThumbnail:[UIImage imageWithData:data]];        
    }
    return self;
}
于 2013-01-14T20:07:42.827 回答