objective-c – 不匹配的-init方法名称
我发现了一个奇怪的情况,在XCode中产生一个我认为不是有效警告的编译器警告.
作为一个例子,我创建了两个类,ClassA& ClassB,它们都有一个名为-initWithSomething的init方法: A级 // ClassA.h #import <Foundation/Foundation.h> @interface ClassA : NSObject { } -(id)initWithSomething:(NSDate *)something; @end // ClassA.m #import "ClassA.h" @implementation ClassA -(id)initWithSomething:(NSDate *)something { if (self = [super init]) { } return self; } @end B级 // ClassB.h #import <Foundation/Foundation.h> @interface ClassB : NSObject { } -(id)initWithSomething:(NSString *)something; @end // ClassB.m #import "ClassB.h" @implementation ClassB -(id)initWithSomething:(NSString *)something { if (self = [super init]) { } return self; } @end 使用ClassA和amp;的另一个类的实现ClassB的 #import "ExampleClass.h" #import "ClassA.h" #import "ClassB.h" @implementation ExampleClass -(void)doSomething { NSDate *date = [NSDate date]; NSString *string = [NSString stringWithFormat:@"Test"]; ClassA *classA = [[ClassA alloc] initWithSomething:date]; ClassB *classB = [[ClassB alloc] initWithSomething:string]; // Produces "Incompatible pointer types sending 'NSString *' to parameter of type 'NSDate *' ClassB *classB2 = [[ClassB alloc] initWithSomething:[NSString stringWithFormat:@"Test"]]; // Does NOT produce a warning ClassB *classB3 = [[ClassB alloc] initWithSomething:@"Test"]; // Produces the same warning as above. [classA release]; [classB release]; [classB2 release]; [classB3 release]; } 这是编译器错误吗?似乎这些行中的任何一行都不会产生警告,特别是因为“classB2”被启动的行不会产生警告. 显然,更明确的方法名称将避免这个问题,但我想知道为什么编译器无法处理这个问题. 注意: 解决方法
我认为问题是alloc返回一个通用id.
这意味着可以在其上调用任何方法,并且编译器将看到导入具有签名-initWithSomething的第一个方法是针对类A的,其中期望类型为NSDate *的对象. 另外,我确实认为方法stringWithFormat返回一个可以与NSDate兼容的id. 编辑: 这个问题的简单解决方案: @interface ClassA +(ClassA *) typeSafeAlloc; // ... @end @implementation ClassA +(ClassA *) typeSafeAlloc { // self is the class variable,which is the same as: // return [ClassA alloc]; return [self alloc]; } @end 并使用ClassB重复该过程(typeSafeAlloc返回ClassB对象) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |