Question

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.

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: To illustrate a bit more what I'm doing with the 2 views, self in this case is a ViewController.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top