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?
The dot syntax is usually applied to declared properties but that’s not mandatory. Using
obj.valueAandobj.valueBdoes work.The error message you’re getting is probably due to the object not having explicit type
MyClass *. For example, the following works:On the other hand:
gives:
because
obj2has typeid, so the compiler doesn’t have enough information to know that.valueAand.valueBare actually the getter methods-valueAand-valueB. This can happen if you place objects of typeMyClassin anNSArrayand later retrieve them via-objectAtIndex:, since this method returns a generic object of typeid.To appease the compiler, you need to cast the object to
MyClass *and only then use the dot syntax. You could accomplish this by:or, if
obj2is declared asid:or, if the object is returned by a method whose return type is
id:Alternatively, you could simply get rid of the dot syntax altogether (my favourite):