将 UIImage 向下转换为 UIImage 子类和调用方法



嗨,所以我有一个名为SASUploadImage的UIImage子类。

这是 SASUploadImage.h

#import <UIKit/UIKit.h>
@class Device;
@interface SASUploadImage : UIImage
@property(nonatomic, weak) NSString *timeStamp;
@end

这是 .m

#import "SASUploadImage.h"
@implementation SASUploadImage
@synthesize timeStamp;
@end

所以在另一个类中,我想设置 timeStamp 属性。我创建了一个名为 sasUploadImage 的属性,并尝试让它引用UIImage对象。这是我的做法:

self.sasUploadImage = (SASUploadImage*)info[UIImagePickerControllerOriginalImage];

info[UIImagePickerControllerOriginalImage] <-- 返回一个 UIImage

现在我明白我不能只引用UIImage对象并调用 setTimeStamp。所以这就是为什么我试图用(SASUploadImage*)来贬低它

但是,我收到以下错误Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage setTimeStamp:]: unrecognized selector sent to instance 0x170086180'

明白为什么我有错误,因为它试图调用一个无法识别的方法,但现在我不确定我是如何向下投射 UIImage 对象,所以它是一个 SASUploadImage 对象。有什么方法可以将UIImage对象变成SASUploadImage对象吗?

这不是

类型转换的工作方式。 info[UIImagePickerControllerOriginalImage] 返回 UIImage 的实例,您不得将其强制转换为 SASUploadImage,因为在内部它只是 UIImage 实例,而不是 SASUploadImage 实例。可以将自定义初始值设定项添加到 SASUploadImage 类,并使用您拥有的映像创建新实例,例如:

.h 文件

#import <UIKit/UIKit.h>
@class Device;
@interface SASUploadImage : UIImage
@property(nonatomic, weak) NSString *timeStamp;
- (instancetype)initWithImage:(UIImage *)img;
@end

.m 文件

- (instancetype)initWithImage:(UIImage *)img {
    return [super initWithCGImage:[img CGImage]]
}

然后

UIImage *img = info[UIImagePickerControllerOriginalImage];
self.sasUploadImage = [[SASUploadImage alloc] initWithImage:img];

您看到的是基本的 OO 行为。不能将 UIImage 强制转换为 UIImage 子类(或任何对象强制转换为其类的子类);只允许/可能相反的情况。毕竟,子类化通常会为类添加特定的逻辑;超类没有这种逻辑,因此不能将对象"视为"子类的实例。虽然苹果具有水果的所有属性,但不能假定未指定的水果具有苹果的所有属性(毕竟,它可能是橙子)。

如果你有一个UIImage并且需要一个SASUploadImage,一个解决方案是添加一个类方法,从UIImage进行SASUploadImage

+ (SASUploadImage *)SASUploadImageFromUIImage:(UIImage *)sourceImage {
   SASUploadImage *result = [SASUploadImage new];
   NSData *imageData = [srcImage TIFFRepresentation]; // important - generates bitmap representation within image!
   NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
   NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageCompressionFactor];
   imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
   SASUploadImage *result = [[NSImage alloc] initWithData:imageData];
   // additional code to copy the image's "content"
   return result;
}

最新更新