Bao
Bao

Reputation: 5

How do I release/delete a UIImageView class?

I'm new to iPhone programming, so I might not even be using the correct methods... anyway, I'm trying to make a game, and when I want to create an enemy I make a new UIImageView, like this:

enemyBird *asdf = [[enemyBird alloc] initWithFrame:CGRectMake(30, -20, 45, 30)];
[self.view addSubview:asdf];

When enemyBird initializes, an NSTimer is made so the enemyBird can fly around and do its own thing. Now, I want to get rid of the bird after it leaves the screen, in this code here:

    if (self.center.y > 500)
    {   //[self dealloc];  //doesn't work
        //[self release];  //doesn't work
        //[self removeFromSuperview];   //this makes it disappear, but the NSTimer is still running
    }

But I don't know how to do that. Am I doing this properly? Or is there an entirely different way I should be doing this? Thanks in advance.

Upvotes: 0

Views: 129

Answers (3)

Vladimir
Vladimir

Reputation: 170829

  1. As view retains all its subviews you can release your imageView right after you add it to controller's view:

    enemyBird *asdf = [[enemyBird alloc] initWithFrame:CGRectMake(30, -20, 45, 30)];
    [self.view addSubview:asdf];
    [enemyBird release];
    
  2. In your timer handler when bird leaves the screen remove it from superview, set reference to nil (to make sure you won't access deallocated instance) and invalidate timer so it won't fire again:

    if (self.center.y > 500)
    {   
        [enemyBird removeFromSuperview];   
        enemyBird = nil;
        [timer invalidate];
    }
    

Upvotes: 1

Mobile Developer
Mobile Developer

Reputation: 5760

for game development better use cocos2d framework: It´s quite easy

Upvotes: 2

user756245
user756245

Reputation:

You have to send removeFromSuperview to your image view, to put it out of the main view. In the same time, you invalidate the timer, and you might be fine.

Also just after alloc/init the image view and add it to the main view, you should release it.

Upvotes: 1

Related Questions