对财产和ivars感到困惑

时间:2014-06-24 04:30:05

标签: ios objective-c xcode properties

我意识到这里已经存在很多财产问题与伊达问题,但经过大量研究后,我似乎无法找到明确的答案。

据我所知,当您声明如下属性时,编译器会自动为您合成支持ivar和两种访问器方法:

@property NSString *myString;

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

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

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

最重要的是,我已经被告知你不应该将myString称为属性,并且“属性”一词只应用于指代合成的两个存取方法当您使用@property指令时编译器为您服务。

你说'#34;我有一个名为myString"的属性真的是错的吗? ,如果这是错的那么说出来的正确方法是什么?

任何帮助清除这一点将不胜感激。我一直在努力巩固财产的理念,而现在整天都在做不同的事情。

2 个答案:

答案 0 :(得分:1)

以下是您的问题的答案 -

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

答案 1 :(得分:0)

我在目标c中几乎是一个菜鸟,但我理解如下:

任何其他OOP语言目标c都有实例变量和getter + setters方法。 基本上每个getter或setter看起来都是一样的,所以XCode允许你使用@property语法自动合成它们。

在XCode的早期版本中,您必须同时声明ivar及其@property + @synthesize,但现在编译器会为您执行此操作。

此代码:

@interface SomeClass : NSObject {
NSString* _myInstanceVar; //declare the ivar
}

@property (non-atomic, strong) myInstanceVar //declare the property+accessors

等同于此代码:

@property (non-atomic, strong) myInstanceVar //declare the ivar+property+accessors

documentation几乎总结了它。

希望无论如何我都会帮助...