Where is my variable ? objective-c
-
30-09-2019 - |
문제
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
해결책
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
다른 팁
I think I found it:
Can you check if this Variable is yours?
besties phil