2012-02-07 82 views
0

我有對象數組的應用程序,這是我存檔,未歸檔保存圖片在IPhone應用程式

-(id)initWithCoder:(NSCoder *)aDecoder{ 
    title = [aDecoder decodeObjectForKey:@"Title"]; 
    image = [aDecoder decodeObjectForKey:@"Image"]; 
    return self; 
} 

-(void)encodeWithCoder:(NSCoder *)aCoder{ 
    [aCoder encodeObject:title forKey:@"Title"]; 
    [aCoder encodeObject:image forKey:@"Image"]; 
} 

UIImage店好這樣?

回答

0

編碼器和解碼器,這是問題的落實都OK

+1

你在iOS 4.3中試過嗎?看起來Apple似乎已經在iOS5中爲UIImage添加了NSCoding支持,但它在iOS4中並不存在,所以我敢打賭它會在4.3模擬器中運行時崩潰,在這種情況下,您仍然需要使用我的解決方案,除非你只向上瞄準5.0。 – 2012-02-11 16:08:54

+0

很抱歉,您的解決方案在ios5上無效 – 2012-02-11 16:20:41

+1

當您在iOS5上嘗試時會發生什麼? – 2012-02-11 16:36:37

4

不,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是否執行任何其他設置。

+0

用戶可以添加JPEG或PNG,我們不知道。如果我的圖像是JPEG格式,它會工作嗎?或者我應該如何實現encodeWithCoder? – 2012-02-08 05:32:30

+1

PNG是無損的,所以它可以用來保存JPEG,沒有任何質量損失,但圖像會比他們需要的更大。我知道你可以使用UIImageJpegRepresentation來保存文件類型。 – 2012-02-08 07:53:07

+1

你爲什麼不接受?它不適合你嗎? – 2012-02-08 10:11:32

相關問題