Using dot notation for instance methods
I was looking at a piec开发者_如何学编程e 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?
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]
精彩评论