我的变量在哪里?目标-c
我通过以下方式初始化视图(图像):
Image *myImageView = [[Image alloc]init];
myImageView.myId = randomImageNumber;
[myImageView initWithImage:myImage];
在 Image 类中,我执行 Log(LOG1) 并获取之前设置的 randomImageNumber。 后来,在同一个班级中,我做了第二个日志(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);
}
“return self”清空了我在头文件中声明并在初始化时设置的 myId。 我该如何防止这种情况发生?
我的头文件如下所示:
@interface Image : UIImageView
{
int myId;
}
@property (assign) int myId;
@end
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想我找到了它:
https://www.google.com/maps/place/Variable/@53.626739,10.025728,17z/data=!3m1!4b1!4m2!3m1!1s0x47b1885360fab615:0x584b82c7dfb5f612
您能检查一下这个变量是否是您的吗?
闺蜜
菲尔
I think I found it:
https://www.google.com/maps/place/Variable/@53.626739,10.025728,17z/data=!3m1!4b1!4m2!3m1!1s0x47b1885360fab615:0x584b82c7dfb5f612
Can you check if this Variable is yours?
besties
phil
在你的代码中添加一些东西。永远不要在一个对象上多次调用 init ,这只会搞砸你的对象。
将其更改为:
这就是您的问题,默认情况下,在初始化
NSObject
的子类时,所有属性都设置为0
(或nil
如果它们是指针)。如果您需要为
myId
设置默认值,请执行以下操作:Couple things in your code. NEVER call init more than once on an object, that just screws up your object.
Change it to this:
That is your problem, by default when initializing a subclass of
NSObject
, all properties are set to0
(ornil
if they are pointers).If you need to have a default value for
myId
then do this: