Where is my variable? objective-c

I initialize the view (image) through:

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

In the Image class, I make Log (LOG1) and get the previously set randomImageNumber. Later, in the same class, I make the second Log (LOG2). Why doesn't my second magazine matter anymore?

Here is my image class implementation file:

@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);
}

"return self" empties myId, which I declared in the header file and which was set during initialization. How can I prevent this?

my Headerfile looks like this:

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

@end
+3
source share
2 answers

A couple in code. NEVER call init more than once on an object that just spins your object.

Change it like this:

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

, NSObject 0 ( nil, ).

myId, :

// Image.m

@implementation

// other code

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

    return self;
}

// other code

@end
+2

Source: https://habr.com/ru/post/1769729/


All Articles