batman
batman

Reputation: 4908

How do I load image to a view?

I'm very new to ios. I'm trying to load a image to my view. Here is my code:

-(void)loadView
{
    UIImageView *imageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    imageHolder.image = image;
    [imageHolder sizeToFit];
    [self.view addSubview:imageHolder];
}

in my class named Test which is a sub class of UIViewController. test.jpg is in the same directory. When I run, I'm getting an error at this line:

UIImage *image = [UIImage imageNamed:@"test.jpg"];

Thread1:EXC_BAD_ACCESS(code=2,address=0xbasd)

where I'm making mistake?

I'm using ios7 and xcode 5

Upvotes: 0

Views: 69

Answers (2)

Kostiantyn Koval
Kostiantyn Koval

Reputation: 8483

I see the problem in your code. It cause infinity loop. loadView - this method is called when the view is empty and you are responsible of creating setting view. When you access self.view your view is empty and loadView method will be called again, and it will finish in infinite loop.

UIImageView *imageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
UIImage *image = [UIImage imageNamed:@"test.jpg"];
imageHolder.image = image;
[imageHolder sizeToFit];
self.view = [[UIView alloc] initWithFrame:frame];
[self.view addSubview:imageHolder];

It's not important where image is located in you file structure. When you add a image to the project. You can do it by - drag and gripping image to the project. or by - "Add Files to Project" When you add image you should select a target project you are adding it to.

Upvotes: 1

Hao
Hao

Reputation: 134

Instead of using a loadView method, I think you should put your code inside -(void)viewDidLoad method. By the way, in Xcode5, you need to right-click on your project and "Add files to project" to add this image file.

-(void)viewDidLoad
{
    [super viewDidLoad];
    UIImageView *imageHolder = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 40, 40)];
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    imageHolder.image = image;
    [imageHolder sizeToFit];
    [self.view addSubview:imageHolder];
}

Upvotes: 0

Related Questions