如何将强id变量转换为UIImage变量?

时间:2012-01-08 16:38:21

标签: iphone ios uiimage

我有一个变量

@property (strong, nonatomic) id dataObject;

它是指向UIImage的指针。我想把它发送到我的新变量。

@property (nonatomic, retain) UIImage *theImage;

当我尝试这样做时,应用程序崩溃时出现此错误: unrecognized selector sent to instance 0x68423b0

如何将其发送到我的新变量?提前谢谢。

contentViewController.h:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "pageAppViewController.h"

@class pageAppViewController;

@interface ViewController : UIViewController

{
    NSArray *content;
    UIImageView *theImageView;
    UIImage *theImage;
}

@property (strong, nonatomic) IBOutlet UIImageView *theImageView;
@property (strong, nonatomic) id dataObject;
@property (nonatomic, retain) UIImage *theImage;

@end

contentViewController.m:

#import "ViewController.h"
#import "pageAppViewController.h"

@implementation ViewController

@synthesize theImageView, dataObject;
@synthesize theImage;


- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    //this is the line that is causing the problems.
    theImage = dataObject;
    theImageView = [[UIImageView alloc] initWithImage: theImage];

    [self.view addSubview:theImageView];   
}
@end

2 个答案:

答案 0 :(得分:0)

当您将属性定义为id时,它会告诉编译器它可以是任何类型的对象。如果您现在想要将此对象分配给已知类型,并且您确定id后面的对象属于同一类型,则可以将其强制转换。

示例

id someObject = [UIImage imageNamed:@"x.png"];

UIImage *myImage = (UIImage*) someObject;

答案 1 :(得分:0)

为什么不在界面中将其设置为UIImage而不是id,为什么是(id)?

@property (strong, nonatomic) UIImage *dataObject;

是NSData类型的图像吗?