我的变量在哪里? Objective-C
-
30-09-2019 - |
题
我通过以下方式初始化一个视图(图像)
Image *myImageView = [[Image alloc]init];
myImageView.myId = randomImageNumber;
[myImageView initWithImage:myImage];
在图像类中,我进行日志(log1),并获取先前设置的随机量产。稍后,在同一类中,我进行第二个日志(log2)。为什么我的第二个日志没有价值?
在这里,我对课堂图像的实现文件:
@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);
}
“返回自我”清空了我在标题文件中声明的myid,并设置为初始化。我如何防止这种情况?
我的HeaderFile看起来像这样:
@interface Image : UIImageView
{
int myId;
}
@property (assign) int myId;
@end
解决方案
在您的代码中近情节。切勿在对象上拨打启动多次,只需拧紧您的对象即可。
将其更改为:
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
不隶属于 StackOverflow