ios - 对属性和 ivars 感到困惑

标签 ios objective-c xcode properties

我意识到这里已经有很多属性与 ivar 的问题,但经过大量研究后我似乎找不到明确的答案。

我了解到,当您声明如下属性时,编译器会自动为您合成支持 ivar 和两个访问器方法:

@property NSString *myString;

仍然让我感到困惑的是,myString 是一个实际的实例变量吗?我问这个的原因是因为你永远不能像这样访问它:

NSLog(@"Value of myString is: %@", myString);

您要么必须使用支持 ivar _myString,要么使用一种 getter 方法,例如 [self myString]self.myString。所以我很困惑,因为通常你可以简单明了地使用变量名。

最重要的是,有人告诉我,您不应该将 myString 作为属性来引用,并且属性这个词应该只用于引用两个访问器方法,它们是当您使用 @property 指令时,由编译器为您合成。

你说“我有一个名为 myString 的属性”真的是错误的吗?如果那是错误的,那么正确的表达方式是什么?

如果您能帮助解决这个问题,我们将不胜感激。我一整天都在努力巩固属性和 ivar 是不同事物的想法。

最佳答案

这里是你问题的答案-

is myString an actual instance variable? - No
Would it really be wrong for you to say "I have a property called myString" , and if that is wrong then what would be the correct way to say it? - No its not wrong to call it.

所以看起来真正让您感到困惑的是命名约定,如果您仔细阅读属性背后的命名约定 -

When you use the @property syntax to declare properties on an object, as described in “Encapsulating Data,” the compiler automatically synthesizes the relevant getter and setter methods (unless you indicate otherwise). If you need to provide your own accessor method implementations for any reason, it’s important to make sure that you use the right method names for a property in order for your methods to be called through dot syntax, for example.

Unless specified otherwise, a getter method should use the same name as the property. For a property called firstName, the accessor method should also be called firstName. The exception to this rule is for Boolean properties, for which the getter method should start with is. For a property called paused, for example, the getter method should be called isPaused.

The setter method for a property should use the form setPropertyName:. For a property called firstName, the setter method should be called setFirstName:; for a Boolean property called paused, the setter method should be called setPaused:.

查看开发者网站以获取详细说明 - https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/Conventions/Conventions.html

关于ios - 对属性和 ivars 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24378359/

相关文章:

objective-c - 自 iOS 10 以来发生的核心数据崩溃

objective-c - Swift 中的 _cmd_/__FUNCTION__

swift - NStableView 不显示我的数据

ios - 如何将分段控件添加到导航栏? (iOS)

ios - AudioQueueNewOutput 与 AudioQueueRef?总是展开 nil

iphone - 如何在 iPhone sdk 中将 NSData 转换为 pdf?

ios - 从 Apple Watch 屏幕捕获视频

ios - UIButton.titleLabel.frame.size 始终为零值

ios - uicollectionview Controller 中的 header 部分。超出范围

ios - 没有任何详细信息的Apple Mach-O链接器警告