为什么我的代码与我一起初始化 NSInteger?
我有一个接口
@interface MyInterface
{
NSInteger _count;
}
@end
然后在我的实现中我只是使用 is as
if (_count==0)
{
//do somthing
}
_count++;
并且它可以工作,即第一次执行时该值实际上是 0,即使我从未将其初始化为零。
是因为NSInteger的默认值是0吗?
Possible Duplicate:
(Objective-)C ints always initialized to 0?
I have an interface
@interface MyInterface
{
NSInteger _count;
}
@end
Then in my implementation I am just using is as
if (_count==0)
{
//do somthing
}
_count++;
And it works i.e. the first time around when this is executed the value is in fact 0 even though I never initialized it to be zero.
Is it because the default value of NSInteger is 0?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您打算编写
==
而不是=
,答案是 Objective-C 类的所有实例变量 (ivars) 都会初始化为 0 或nil
当对象被创建时。请参阅问题(Objective-)C 整数始终初始化为 0? 。如果您实际上使用单个
=
编写了if (_count = 0)
,那么这并没有达到您的预期 - 它会将 0 分配给_count
,然后测试它是否非零(表达式if (x)
测试x
是否非零)。由于您刚刚为其分配了 0,因此它不是非零,因此测试总是会失败。Assuming you meant to write
==
instead of=
, the answer is that all of the instance variables (ivars) of an Objective-C class get initialized to 0 ornil
when the object gets created. See the question (Objective-)C ints always initialized to 0?.If you actually wrote
if (_count = 0)
with a single=
, then that's not doing what you expected -- it's assigning 0 to_count
, and then testing if it's non-zero (the expressionif (x)
tests ifx
is non-zero). Since you just assigned 0 to it, it's not non-zero, so the test will always fail.更改 if 语句以
记住双等于是比较,单等于是赋值
change your if statement to
remember double equals is comparison, single equals is assignment
您使用
此功能会将值
0
设置为变量_count
,如果此操作成功,则会执行{}
之间的代码来测试变量的值使用比较运算符
==
you are using
this will set value
0
to variable_count
, and if this action success, code between{}
is executedto test value of variable use comparison operator
==