views:

205

answers:

3

I'm trying to return a double from another object then store that into a new double but i'm getting the error incompatible types in initialization. What am I missing here?

double gradePoints = 0.0;
double other = [aCourse getGradePoints];
gradePoints = gradePoints + other;

This is in my other object

- (double) getGradePoints{
   return 12.0;
 }
+2  A: 

Is the reference to aCourse typed or is it an id? If I remember correctly, if the class of aCourse isn't known to the compiler, it assumes that the result of all method calls is type id.

Geoff Reedy
Yes it's typed to my custom classCourse *aCourse = [[Course alloc]init];
aahrens
Not quite. If the compiler doesn't know of any method matching the signature (`-getGradePoints` in this case) it assumes the return type to be `id`, and any arguments to be `id, ...` (or just `...`, I can never remember). The method is clearly missing from the interface declaration of Course.
Williham Totland
+7  A: 

Most likely you have forgotten to add the getGradePoints method to an interface declaration: This will result in the method being implicitly declared as -(id)getGradePoints; resulting in the warning you are seeing.

Williham Totland
This seems like the only reasonable explanation.
Toon Van Acker
A: 

The getter/setter kvo standard defines getters in the form of getPropertyName. If you have a property called gradePoints the compiler will interpret getGradePoints as the getter for that property and if the property is not defined as a double, it will complain.

Even defining a local variable like this:

double gradePoints = 0.0;
double other = [aCourse getGradePoints];

... may confuse the compiler because it may try to process getGradePoints as the getter for gradePoints.

Objective-C relies on naming conventions to find specific types of methods because it can't assume at compile time what methods an object in a particular circumstance will have.

In general you should avoid using method names that begin with "get" and "set" because the compiler wants to treat them as getter and setter methods for properties. The potential for compiler confusion is high.

I try to use prefixes like "fetch", "grab", "obtain" etc instead of "get" just to be safe.

TechZen
Actually, aren't those defined as just `-propertyName`? Or both?
Williham Totland
The old school 'get' is still active. I've hit problems in Obj-C 2.0 by accidentally creating a `getPropertyName` method (not intended as a getter) that returned a different type from than the property. It's important to name your methods carefully in Obj-C.
TechZen