变量使用self.foo还是_foo

本文探讨了在 Objective-C 编程中使用 self.foo 和 _foo 访问实例变量的争论。一方面,使用 self.foo 被认为更易于维护,能更好地处理 KVO 和内存管理,并且符合 Apple 的推荐风格;另一方面,直接访问 _foo 被认为可以区分公共和私有成员,减少消息发送带来的潜在问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

selfOR_

又开始了这个问题的讨论,哈哈,直接迁移到swift??这个问题在ef oc 2.0中也有过列举各自的一些优缺点.

原文链接

The Debate Over Direct Access 变量使用的争议

At lunch today a few of us discussed the issue of using self.foo vs. _foo in Objective-C.

We had people on two sides. I’ll lay out the arguments.

(Note: this isn’t even a debate in Swift, which is one of the reasons I’m eager to switch to Swift.)

self.foo

This side argues against declaring ivars, and argues that all properties — external and internal — should be synthesized (usually implicitly).

The only cases where you access the underlying storage directly — reference _foo, in other words — is in init, dealloc, and in custom accessors. Otherwise you use self.foo everywhere.

除了在init,dealloc ,自定义的访问方法中,其他的地方都使用self.的形式.

Reasons:

  • It’s a simple rule to remember. You don’t have to remember whether a property is internal or external.(便于记忆)
  • A given property can have custom accessors, or not, and you still treat it the exact same way. Adding or removing custom accessors does not mean you have to go looking for all the references to that property and possibly change them.(修改方便)
  • You’re treating your object’s interface as an API. Inside the object you have more API than outside callers can see, which is fine. It’s still all API.(作为API访问)
  • You have to worry less about KVO if you always use self.foo instead of _foo.(不用担心KVO)
  • You’re more likely to get memory management right if you use self.foo. (This is much less of an issue with ARC, I grant.)(手动内存管理的时候,更加方便.)
  • Subclasses are more likely to get things right if you use self.foo.(子类化方便)
  • Apple seems to advocate this style. (Not always consistently.)(Apple推荐....)

_foo

This side argues that using direct storage access inside an object is the way to go.

Reasons:

  • There’s a useful distinction between public and private. The code for an object is private, and it’s therefore fair to access storage directly. An object has one API — its public API — and inside the object you can do whatever makes sense.(公私分明)
  • Any time you send a message, it’s possible that anything could happen, including reentrancy bugs and so on. Accessing storage directly does not have that problem.(容易引入bug)
  • Sending a message may have performance issues. (Probably not. But it’s possible.)(可能会存在性能问题)

Okay — I don’t fully understand this side of the argument. I did the best I can to explain it, but I’m most definitely in the self.foo camp.

But smart people disagree with me.

Why am I wrong, and why is _foo better?

undefined
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值