Objective-C代码报错及警告求助:多方法匹配、指针属性变更等
Objective-C代码错误与警告修复方案
错误1:Multiple methods named 'setBounds:' found with mismatched result, parameter type or attributes
原因
系统框架(如UIKit)中的UIView类已存在setBounds:方法,参数为CGRect类型;你的Circle类自定义了同名方法,参数是自定义的ShapeRect结构体,编译器无法区分二者的方法签名,导致冲突。
解决方法
修改Circle类中setBounds:方法的名称,避免与系统方法重名,例如改为setCircleBounds::
修改后的Circle头文件:
@interface Circle : NSObject { ShapeColor fillColor; ShapeRect bounds; } - (void) setFillColor: (ShapeColor) fillColor; - (void) setCircleBounds: (ShapeRect) bounds; // 修改方法名 - (void) draw; @end // Circle
修改后的Circle实现:
- (void) setCircleBounds: (ShapeRect) b { bounds = b; }
main函数中调用时改为:
[shapes[0] setCircleBounds: rect0];
错误2:Passing '__strong id *' to parameter of type '__unsafe_unretained id *' changes retain/release properties of pointer
原因
drawShapes函数的参数id shapes[]默认被编译器视为__unsafe_unretained id *类型,而main函数中定义的id shapes[1]在ARC环境下默认是__strong类型,二者内存所有权属性不匹配,触发报错。
解决方法
方法1:显式指定函数参数为__strong类型
void drawShapes (__strong id shapes[], int count) { int i; for (i = 0; i < count; i++) { id shape = shapes[i]; [shape draw]; } }
方法2:改用NSArray存储对象(推荐,符合Objective-C最佳实践)
void drawShapes (NSArray *shapes) { for (id shape in shapes) { [shape draw]; } } int main (int argc, const char * argv[]) { ShapeRect rect0 = { 0, 0, 10, 30 }; Circle *circle = [Circle new]; [circle setCircleBounds: rect0]; [circle setFillColor: kRedColor]; NSArray *shapes = @[circle]; drawShapes(shapes); return 0; }
警告:Expression which evaluates to zero treated as a null pointer constant of type 'CGColorRef _Nullable'
原因
推测是colorName函数的实现中,返回了整数0作为CGColorRef类型的值,但CGColorRef是指针类型,应使用NULL或合法的CGColorRef对象;若colorName实际是返回字符串(从NSLog的%@格式符推测),则可能是函数返回类型写错,需改为NSString*。
解决方法
情况1:colorName返回CGColorRef
CGColorRef colorName(ShapeColor color) { switch (color) { case kRedColor: return [UIColor redColor].CGColor; // 其他颜色分支 default: return NULL; // 替换原来的0 } }
情况2:colorName返回字符串(符合NSLog的%@格式)
NSString *colorName(ShapeColor color) { switch (color) { case kRedColor: return @"red"; // 其他颜色分支 default: return nil; } }
内容的提问来源于stack exchange,提问作者Phone Htet Aung
相关产品推荐
相关产品推荐

