访问实例变量的语法? (目标C) [英] Syntax for accessing instance variables? (Objective-C)
问题描述
在Objective-C中访问实例变量的正确语法是什么?
What is the proper syntax for accessing an instance variable in Objective-C?
假设我们有这个变量:
@interface thisInterface : UIViewController {
NSMutableString *aString;
}
@property (nonatomic, retain) NSMutableString *aString;
它是合成的.
当我们要访问它时,我们首先要分配和初始化它.在Objective-C中编程大约一个月以来,我已经看到了两种不同形式的语法.我见过人们只是简单地aString = [[NSMutableString alloc] initWithString:@"hi"]
,他们在其中分配字符串.我还看到人们以self.aString
开始它,然后他们继续初始化他们的ivar.我想我只是想找出初始化实例变量的最正确方法是什么,因为在前面的示例中,我从中收到了EXC_BAD_ACCESS错误.在添加self.
之后,它没有出现.
When we want to access it, we first would want to allocate and initialize it. Having programmed in Objective-C for about a month now, I've seen two different forms of syntax. I've seen people do simply aString = [[NSMutableString alloc] initWithString:@"hi"]
, where they allocate the string like that; I've also seen people start it off with self.aString
and then they proceed to initialize their ivar. I guess I'm just trying to figure out what is the most proper way of initializing an instance variable, because with the former example, I have received EXC_BAD_ACCESS errors from it. After prepending the self.
though, it didn't appear.
如果这是一个重复的问题,请原谅我,但是在阅读了有关SO的一些帖子后,这使我感到好奇.我正在尝试使用Objective-C学习正确的语法,因为我更喜欢正确而不是草率.
Forgive me if this is a duplicate question, but after reading some posts on SO, it's made me curious. I'm trying to learn the proper syntax with Objective-C because I prefer being proper rather than sloppy.
推荐答案
如果您声明了一个属性,并在.m文件中@synthesize
对其进行了设置,则只需这样设置即可:
If you have declared a property and @synthesize
it in the .m file, you simply set it like this:
self.aString = @"hi"; // or [[NSMutableString alloc] initWithString:@"hi"];
使用self.varName
可以利用属性声明的实际作用-它可以处理新值的保留(因为属性具有retain
属性),为您释放旧值等.
Using self.varName
takes advantage of what your property declaration actually does- it handles retention of the new value (since your property has the retain
attribute), releasing the old value, etc for you.
如果您只是这样做:
aString = someValue;
...您可能正在泄漏aString
中的原始值,因为不使用self.aString
您是直接通过属性访问变量.
... you may be leaking the original value that was in aString
, since without using self.aString
you are accessing the variable directly vs through the property.
这篇关于访问实例变量的语法? (目标C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!