爲什麼當我嘗試使用NSKeyedArchiver對其進行編碼和解碼時,此代碼段中的UIImage不會恢復到其原始狀態?爲什麼不能成功解碼UIImage?
我期待「decodeImage」包含解碼後的圖像,但它只是NULL。
// Any image here seems to repro the issue
UIImage *image = [UIImage imageNamed:@"soda.jpg"];
// This prints YES (1), just a sanity check.
NSLog(@"Confirms %d", [[UIImage class] conformsToProtocol:@protocol(NSCoding)]);
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[coder encodeObject:image forKey:@"image"];
[coder finishEncoding];
// I would expect this to be large, instead it's < 1kb.
NSLog(@"Data length is: %zu", (unsigned long)data.length);
NSKeyedUnarchiver *decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
// This prints YES (1)
NSLog(@"containsValueForKey returns %d", [decoder containsValueForKey:@"image"]);
// decodedImage is NULL here, even though containsValueForKey returned YES
UIImage *decodedImage = [decoder decodeObjectForKey:@"image"];
[decoder finishDecoding];
在這種情況下,我沒有尋找一種解決方法,例如先將UIImage轉換爲NSData並對其進行編碼。原因是我試圖重現一個不相關的代碼,它使用了類似這樣的代碼,我試圖理解它。
如果我首先通過nsdata返回圖像並返回到uiimage,代碼將按預期工作,爲什麼?
UIImage *originalImage = [UIImage imageNamed:@"soda.jpg"];
NSData *imageData = UIImagePNGRepresentation(originalImage);
UIImage *image = [UIImage imageWithData:imageData];
我認爲這個奇怪的事實與使用[UIImage imageNamed:]創建的UIImage沒有像其他UIImages一樣的序列化,也許是因爲它知道圖像來自應用程序包... –