使用点表示法作为实例方法 [英] Using dot notation for instance methods
问题描述
我今天正在看一段代码,注意到这个特定的编码器使用点表示法来访问实例方法(这些方法不使用值,它们只是返回值).
I was looking at a piece of code today and notice that this particular coder use dot notation to access instance methods (these methods don't take values, they just return value).
例如:
@interface MyClass : NSObject {
}
-(double)add;
@end
@implementation MyClass
-(double)valueA {
return 3.0;
}
-(double)valueB {
return 7.0;
}
-(double)add {
return self.valueA + self.valueB;
}
@end
他在整个代码中都做到了这一点,并且编译器没有抱怨,但是当我像上面的示例一样在我的代码中尝试该操作时,出现以下错误:在不是结构或联合的内容中请求成员"valueA"".我想念什么,知道吗?
He did this through out his code and the compiler doesn't complain, but when I try it in my code like the example above I get the following error: "Request for member "valueA" in something not a structure or union". What am I missing, any idea?
推荐答案
点语法通常应用于声明的属性,但这不是强制性的.使用 obj.valueA
和 obj.valueB
确实可以.
The dot syntax is usually applied to declared properties but that’s not mandatory. Using obj.valueA
and obj.valueB
does work.
您收到的错误消息可能是由于对象没有明确的类型 MyClass *
.例如,以下作品:
The error message you’re getting is probably due to the object not having explicit type MyClass *
. For example, the following works:
MyClass *obj1 = [MyClass new];
NSLog(@"%f %f %f", obj1.valueA, obj1.valueB, [obj1 add]);
另一方面:
MyClass *obj1 = [MyClass new];
NSLog(@"%f %f %f", obj1.valueA, obj1.valueB, [obj1 add]);
id obj2 = obj1;
NSLog(@"%f %f %f", obj2.valueA, obj2.valueB, [obj2 add]);
给予:
error: request for member ‘valueA’ in something not a structure or union
error: request for member ‘valueB’ in something not a structure or union
因为 obj2
的类型为 id
,所以编译器没有足够的信息来知道 .valueA
和 .valueB
实际上是getter方法 -valueA
和 -valueB
.如果将类型为 MyClass
的对象放置在 NSArray
中,然后通过 -objectAtIndex:
检索它们,则可能会发生这种情况,因为此方法返回通用对象类型为 id
.
because obj2
has type id
, so the compiler doesn’t have enough information to know that .valueA
and .valueB
are actually the getter methods -valueA
and -valueB
. This can happen if you place objects of type MyClass
in an NSArray
and later retrieve them via -objectAtIndex:
, since this method returns a generic object of type id
.
要安抚编译器,您需要将对象强制转换为 MyClass *
,然后才使用点语法.您可以通过以下方式完成此操作:
To appease the compiler, you need to cast the object to MyClass *
and only then use the dot syntax. You could accomplish this by:
MyClass *obj2 = obj1;
// or
MyClass *obj2 = [someArray objectAtIndex:someIndex];
// and then
obj2.valueA
,或者,如果将 obj2
声明为 id
:
or, if obj2
is declared as id
:
((MyClass *)obj2).valueA
,或者,如果对象是由返回类型为 id
的方法返回的:
or, if the object is returned by a method whose return type is id
:
((MyClass *)[someArray objectAtIndex:someIndex]).valueA
或者,您可以完全摆脱点语法(我的最爱):
Alternatively, you could simply get rid of the dot syntax altogether (my favourite):
[obj2 valueA]
[[someArray objectAtIndex:someIndex] valueA]
这篇关于使用点表示法作为实例方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!