Raluca Lucaci
Raluca Lucaci

Reputation: 2153

Uiimage wrong initialization and EXC_BAD_ACCESS

I have a class where I have:

static UiImage *image;

In the same class I have a method setImage (UiImage*) imag

{self.image= [[Uiimage alloc]init]; //*
self.image=imag;}

In another class I have

[myFirstClass setImage: (uiimage)]

This uiimage exists .

The app frezees and it stops at (*). Houndreds of proces start at this line. I also see EXC_BAD_ACCESS

Thanks

Upvotes: 0

Views: 130

Answers (3)

Damo
Damo

Reputation: 12900

You have declared image

static UiImage *image;

Is that because you wish to initialise it once and thereafter refer to it - as a constant? If so, a good way to do this is to override the getter accessor method for image.

// foo.h
class foo {
    UIImage* image_;
}

@property (nonatomic, retain) UIImage* image;

// foo.m
@synthesize image = image_;

-(UIImage*)image {
    if (image_ == nil) {
        //set the image here
        image_ = [[UIImage alloc] init];    
    }
    return image_
}

Then in client code, the first time you refer to foo.image it will be instantiated. The second and every other time you refer to it, it will already have a value.

// elsewhere in foo.m

UIImageView* fooImageView = [[UIImageView alloc] initWithImage:self.image];

// bar.m

UIImageView* barImageView = [[UIImageView alloc] initWithImage:foo.image];

See this SO answer also for reference.

Upvotes: 1

Simon Lee
Simon Lee

Reputation: 22334

Use the following instead...

- (void)setImage (UiImage*)anImage {
  [image release];
  image = [anImage retain];
}

Upvotes: 1

ksh
ksh

Reputation: 1904

If you have a property image then you're getting into infinite loop by calling your setter from setter.

Upvotes: 3

Related Questions