【问题标题】:Encode array of images exception编码图像数组异常
【发布时间】:2012-03-23 09:14:08
【问题描述】:

我尝试使用 UIImages 对数组进行编码。

然后我调用“保存”函数

NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"SavedUserData"];
[NSKeyedArchiver archiveRootObject: self toFile:filePath];

我得到了行的异常
[encoder encodeObject:recipePhotoList forKey:@"recipePhotoList"]; //带有图像的数组

 -[UIImage encodeWithCoder:]: unrecognized selector sent to instance 0x1b1380
2012-03-23 11:59:43.694 fishmarket[261:1a0f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage encodeWithCoder:]: unrecognized selector sent to instance 0x1b1380'

在 5+ iOS 上它运行良好,在 4.3 上我有这个问题。

【问题讨论】:

    标签: objective-c encode


    【解决方案1】:

    这是因为 UIImage 在 iOS 5 之前不支持 NSCoding。检查 iOS 5.0 API diff.

    【讨论】:

    • 我猜是这样。但是我用那个外壳来编码它?编码为字节数组?
    【解决方案2】:

    为 iOS 编码/解码 UIIMage 的一些替代方法

    + (void)saveImage:(UIImage*)image withName:(NSString*)imageName
    {
        if (image != nil)
        {
            NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString* documentsDirectory = [paths objectAtIndex:0];
            NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
            NSData* data = UIImagePNGRepresentation(image);
            [data writeToFile:path atomically:YES];
        }
    }
    
    + (UIImage*)loadImageNamed:(NSString*)imageName
    {
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentsDirectory = [paths objectAtIndex:0];
        NSString* path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:imageName]];
        UIImage* image = [UIImage imageWithContentsOfFile:path];
        return image;
    }
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2021-10-08
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多