开发者

Multiple methods warning

I'm currently learning Objective C and in the process I've made the silly little program below. The program compiles fine - however I get the warning "multiple methods named '-setName:' found".

I've only interfaced and implemented the method once.

What does this warning mean, and how do I correct it?

#import <Foundation/Foundation.h>

// these are the three yoga-exercises we can perform

typedef enum {
    kCobra,
    kUniversal,
    kDog
} ExerciseName;

// translating our variables into human

NSString *nameExercise (ExerciseName nameExercise)
{
    switch (nameExercise) {
        case kCobra:
            return @"Cobra Pose";
            break;
        case kUniversal:
            return @"Universal Stretch";
            break;
        case kDog:
            return @"Dog Pose";
            break;
    }

    return @"no clue!";

} // nameExercise


@interface Exercise : NSObject
{
    ExerciseName name;
}

-(void) setName: (ExerciseName) name;
-(void) exerciseDo;

@end


@implementation Exercise

-(void) setName: (ExerciseName) n {
    name = n;
} // setName

-(void) exerciseDo {
    NSLog(@"Exercise: %@",
          nameExercise(name));
}

@end


void executeExercises(id exercises[], int count) {

    int i;

    for(i=0; i<count; i++) {
        id exercise = exercises[i];
        [exercise exerciseDo];
    }
}

int main (int ar开发者_开发百科gc, const char * argv[]) {

    id exercises[1];

    exercises[0] = [Exercise new]; // initiating an object of class Exercise
    [exercises[0]   setName:kDog];

    executeExercises(exercises, 1);

    return 0;

} //main


the meaning of the message is that there are multiple selectors with the name setName: in the translation (that is, it is declared in at least on other place among all included headers). the compiler may choose the wrong selector (which can introduce undefined behavior).

you can typically correct the problem using one (or more) of the following approaches:

1) rename the method to a unique name: e.g. setExerciseName may be ok, if not used in other translations.

2) match the signature of the other selector. e.g. setName:(NSString *)name

3) use type safety:

Exercise * ex = [Exercise new];
[ex setName:kCobra];

4) cast the variable to the type: [(Exercise*)exercise setName:kCobra];

5) restore the type with a new variable: Exercise * ex = exercise;

since you have declared the var as an id, you have erased the type, and it means that the object may respond any visible selector. in general, you should not erase the type in this manner, except when truly necessary.

the best approach i see is a combination of 1 and 3:

[ex setExerciseName:kCobra];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜