views:

82

answers:

1

I am trying to create a UIImageView called theImageView in the touchesBegan method that I can then then move to a new location in touchesMoved. Currently I am receiving an "undeclared" error in touchesMoved where I set the new location for theImageView.

What can I do to keep theImageView in memory between these two methods?

EDIT: I am unable to declare theImageView in the @interface as I need to create an image every time a certain point is touched.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    ...
    UIImageView *theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]];
    theImageView.frame = CGRectMake(263, 228, 193, 300);
    [theImageView retain];
    ...
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    ...
    theImageView.frame = CGRectMake(300, 300, 193, 300);
    ...
}
+6  A: 

You have declared the variable in a method/function, which makes it a local variable (that is, a variable which exists only inside that function). To make it available in other methods you have to declare it as instance variable in your class's @interface.

Costique
Thank you for your answer. I'm sorry but I meant to say that I am unable to do this because I am trying to create a new UIImageView object every time a predetermined area of the screen is touched. This means that I will need to create these objects dynamically and therefore I am unable to declare them in the @interface. Is there any other way of going about this? Thanks again for your help.
Chris
@Chris: I don't see why you think you're unable to do this. You can reassign instance variables to point to new objects.
Chuck
Or have an instance variable to hold an NSMutableArray in which you put UIImageViews.
Peter Hosey
@Chris: this *is* the right answer. Try it and see. All you need to do is declare the UIImageView in the interface, delete `UIImageView` from the first line of `touchesBegan:withEvent:`. Then, when you are sure it works, add `[theImageView release]` above the alloc and delete the line that says `[theImageView retain]` and that will stop all the memory leaks.
JeremyP
On the other hand, if you want to keep all of the image views, you'll need to put them in an array just before you release them.
JeremyP