views:

38

answers:

1

So I have just started learning objective c having a little Java experience and this site has been really helpful for answering loads of my questions, but I've hit an issue I can't quite fathom. Theres a fair amount to be read on the topic but I can't quite find where I've gone wrong.

So I read this:

Objective C does not support class data members (i.e. data shared by all objects of the same class), however, they can be emulated through the use of the static modifier. For example, declaring a static int count variable in the implementation file of the Employee class would result in all Employee objects sharing a single integer variable called count.

but I seem to have ended up with this functionality without trying... and I don't want it!

The scenario is that I have a Category of UIImageView in which I'm declareing a global variable (just below my @implementation line) to count a particular event and have it used in my new methods.

@implementation UIImageView (Draggable)    
int touchesCount = 0;    
// methods ...

Everything works fine if I have a single UIImageView. However when I create and add a second instance of UIImageView this count variable is being shared between the two giving unexpected behaviour.

Figure it may be relevant to show how I'm creating the objects:

UIImageView *myImageView = [[UIImageView alloc] initWithFrame:myImageRect]; 
UIImageView *myImageView2 = [[UIImageView alloc] initWithFrame:myImageRect];
// ... (create, manipulate and set 2 images to the 2 views)
[self.view addSubview:myImageView];
[self.view addSubview:myImageView2];

other than that any suggestions on where I might be going wrong?

thanks!

EDIT: Illustrate a bit more what I'm doing with the 2 views, self in this case is a ViewController

+2  A: 

What you are looking for are instance variables, but categories can't add those to an interfaceApple:

Note that a category can’t declare additional instance variables for the class; it includes only methods.

You should be using inheritance instead:

@interface MyView : UIImageView {
    int touchesCount;
}
// ...
@end
Georg Fritzsche
I've altered my code per your suggestion and it's now working as intended. Thanks for your help.
Faylen