views:

40

answers:

1

I initialize a view(Image) through:

Image *myImageView = [[Image alloc]init];
    myImageView.myId = randomImageNumber;
    [myImageView initWithImage:myImage];

At the Image class I do a Log(LOG1) and get the previously set randomImageNumber. Later on, in the very same Class, I do a second Log(LOG2). Why does my second log have no value anymore ?

Here my implementation-file of the Class Image:

@synthesize myId;
-(id) initWithImage: (UIImage *) anImage
{
    NSLog(@"LOG1%d",myId);
    if ((self = [super initWithImage:anImage]))
    {
        self.userInteractionEnabled = YES;
    }
    return self;
}

}
-(void)touchesBegan...
....
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  NSLog(@"LOG2%d",myId);
}

The "return self" empties myId which i declared in the header-file and which was set at the initialisation. How do I prevent that ?

my Headerfile looks like this:

@interface Image : UIImageView 
{
   int myId;
}
@property (assign) int myId;

@end
+3  A: 

Couple things in your code. NEVER call init more than once on an object, that just screws up your object.

Change it to this:

Image *myImageView = [[Image alloc] initWithImage:myImage];
myImageView.myId = randomImageNumber;

That is your problem, by default when initializing a subclass of NSObject, all properties are set to 0 (or nil if they are pointers).

If you need to have a default value for myId then do this:

// Image.m

@implementation

// other code

-(id) initWithImage:(UIImage *) image
{
    if (self = [super initWithImage:image])
    {
         self.myId = randomImageNumber;
    }

    return self;
}

// other code

@end
Richard J. Ross III
Ok, I tried this kind of initialization, but in this case even my first Log didn't give me a value -> just 0 like you said. How could I initialize my Image-Class without loosing my instance-variables declared in the header(of the Image-Class) ?
algro
@algro The first log *should* give 0. Instance variables are always empty until they're initialised -- they cannot be given a value in the interface, only declared. You should probably post what's in your header file, since it sounds like there is some misunderstanding here.
walkytalky
ok, I posted my header-file... It doesn't matter if the first log is 0. I need it only if touched -> LOG2. At that point the value should be set no ?
algro
@algro Yep. Assuming you don't have other calls changing the value, once you've set the property it should remain set.
walkytalky
But at the moment it doesn't. Shouldn't I somehow alloc the value in the initializing-Class ? I heard Multiple threads / Memory management could be the issue, but I don't know how to implement...
algro
If you need to have `myId` set to a default value on initialization, then call the code in my edited answer
Richard J. Ross III
Ok I found out that the touched region doesn't correspond with the underlying image
algro