iVars,有和没有自我? [英] iVars, With and Without self?

查看:75
本文介绍了iVars,有和没有自我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道自己在对象中扮演的角色。我理解,写 [[self dataForTable] count] 直接指向包含在该对象中的iVar。但如果你错过自我并直接指定iVar [dataTable count] 如何不同,你通过使用self保护什么是它只是为了唯一地指定一个iVar而不是一些类似的局部变量?

I am just curious about the role that self plays within an object. I understand that writing [[self dataForTable] count] refers directly to the iVar contained in that object. But if you miss self off and directly specify the iVar [dataTable count] how does that differ, what are you protecting against by using self, is it just to uniquely specify an iVar rather than maybe some similar local variable?

@implementation ViewController
@synthesize dataForTable;

...

NSUInteger dataCount = [[self dataForTable] count];

非常感谢。

Gary。 p>

Gary.

推荐答案

写入[[self dataForTable] count] 不直接指向iVar。有一些幕后的东西在进行...

Writing [[self dataForTable] count] does not refer directly to the iVar. There's some behind-the-scenes stuff going on...

如果你在你的代码中使用一个ivar没有自己,那是直接访问ivar。如果你使用[self someIvarName]或self.someIvarName,你实际上是发送一个消息给对象(这是自我)。运行时尝试解析此消息,并将使用多种机制之一:如果已定义具有匹配名称的方法,则将使用该方法,如果不存在此类方法(或属性),则键值编码将默认使用一个同名的ivar。

If you use an ivar in your code without self, that's direct access to the ivar. If you use either [self someIvarName] or self.someIvarName, you're actually sending a message to the object (which is self). The runtime attempts to resolve this message and will use one of a number of mechanisms: If you have defined a method with a matching name, that method will be used, if no such method (or property) exists, then key-value-coding will use an identically named ivar by default.

至于影响,这将根据你的代码不同。例如,如果您的属性是保留属性(而不是分配的属性),则之间有非常显着的区别:

As for the impact, this will differ based on your code. For example if your property is a retained property (as opposed to assigned), there's a very significant difference between:

someVar = nil

self.someVar = nil

合成的setter将正确释放someVar,然后将其设置为nil ,而在第一个例子中,你现在泄漏的内存。这只是差异的一个例子。

The synthesized setter will properly release someVar before setting it to nil, whereas in the first example, you've now leaked memory. This is just one example of the difference.

这篇关于iVars,有和没有自我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆