Using dot notation for instance methods

雨燕双飞 提交于 2019-12-14 04:25:25

问题


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).

For example:

@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

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?


回答1:


The dot syntax is usually applied to declared properties but that’s not mandatory. Using obj.valueA and obj.valueB does work.

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]);

On the other hand:

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]);

gives:

error: request for member ‘valueA’ in something not a structure or union
error: request for member ‘valueB’ in something not a structure or union

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.

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

or, if obj2 is declared as id:

((MyClass *)obj2).valueA

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]


来源:https://stackoverflow.com/questions/6364555/using-dot-notation-for-instance-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!