[英]Pass by value in Objective-C?
I'm looking at understanding objective-c and I came into a problem in tapping the screen and incrementing the count variable which I store in my appdelegate. 我正在寻找对Objective-C的理解,并且在点击屏幕并增加存储在我的appdelegate中的count变量时遇到问题。
- (void)updateLabel:(NSInteger)num {
NSString *s = [[NSString alloc] initWithFormat:@"%@", num];
countLabel.text = s;
[s release];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
TestAppDelegate *aDel = (TestAppDelegate *)[UIApplication sharedApplication].delegate;
aDel.count++;
NSInteger num = aDel.count;
[self updateLabel:num];
}
I get the EXC_BAD_ACS which to me says I'm trying to access something I'm not. 我得到EXC_BAD_ACS,对我来说,我正在尝试访问不是我所访问的内容。 It looks like I cannot send updateLabel the num variable because the scope of the primitive type goes away at the end of the method and then when updateLabel tries to access it, I get the error?
看来我无法向num变量发送updateLabel,因为原始类型的范围在方法末尾消失了,然后当updateLabel尝试访问它时,我得到了错误? I wanted to know if I understood this concept correctly.
我想知道我是否正确理解了这个概念。 Thanks.
谢谢。
// format specifier for integer is %d, not %@ NSString *s = [[NSString alloc] initWithFormat:@"%d", num];
num
is not out of scope here. num
在这里不超出范围。 You are passing it by value to updateLabel
. 您正在按值将其传递给
updateLabel
。 Please also check that countLabel
is not already released when you are calling updateLabel
. 调用
updateLabel
时,还请检查countLabel
是否尚未释放。
And you can pass aDel.count
directly to the updateLabel
. 您可以将
aDel.count
直接传递给updateLabel
。 There is no need of temporary num
variable. 不需要临时的
num
变量。
[self updateLabel:aDel.count];
The problem might be that NSInteger
is not an object, see its definition by cmd-clicking the keyword: 问题可能是
NSInteger
不是对象,请通过cmd单击关键字来查看其定义:
#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE …
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
Which means that your method to update the label should look a bit like this: 这意味着您更新标签的方法应如下所示:
- (void) updateLabel: (NSInteger) num {
countLabel.text = [NSString stringWithFormat:@"%i", num];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.