不,UIImage不符合NSCoding協議。
要保存圖像,請使用UIImageJPEGRepresentation(image, quality)
或UIImagePNGRepresentation(image)
將其轉換爲NSData,然後您可以將NSData對象保存在編碼器中,因爲它符合NSCoding。
像這樣:
-(id)initWithCoder:(NSCoder *)aDecoder{
if ((self = [super init])){
title = [aDecoder decodeObjectForKey:@"Title"];
image = [UIImage imageWithData:[aDecoder decodeObjectForKey:@"ImageData"]];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:title forKey:@"Title"];
[aCoder encodeObject:UIImagePNGRepresentation(image) forKey:@"ImageData"];
}
PS,我假設你正在使用ARC?如果不是,則需要在initWithCoder方法中保留這些值,因爲decodeObjectForKey:
會返回一個自動釋放對象。我還重寫了你的initWithCoder以包含正常的超/無檢查,這是最佳實踐。
請注意,您可能希望使用self = [self init]
或self = [super initWithCoder:aDecoder]
而不是self = [super init]
,這取決於您的超類是什麼以及您的init是否執行任何其他設置。
你在iOS 4.3中試過嗎?看起來Apple似乎已經在iOS5中爲UIImage添加了NSCoding支持,但它在iOS4中並不存在,所以我敢打賭它會在4.3模擬器中運行時崩潰,在這種情況下,您仍然需要使用我的解決方案,除非你只向上瞄準5.0。 – 2012-02-11 16:08:54
很抱歉,您的解決方案在ios5上無效 – 2012-02-11 16:20:41
當您在iOS5上嘗試時會發生什麼? – 2012-02-11 16:36:37