通常,ARC语义问题-没有已知的选择器实例方法的解决办法是检查是否正确命名使用了实例方法。以下是一个示例:
在下面的示例中,我们定义了一个名为Person的类,并使用init方法来创建新对象。但是,该代码抛出了ARC语义错误,因为在类定义中没有定义init方法。
// Person.h
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
- (void)sayHello;
@end
// Person.m
@implementation Person
- (void)sayHello {
NSLog(@"Hello World!");
}
@end
// main.m
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person* p1 = [[Person alloc]initWithName@"John"]; // ARC Semantic Issue - No Known Instance Method For Selector 'initWithName:'
[p1 sayHello];
}
return 0;
}
要解决此问题,我们需要为Person类定义一个新的init方法,并且确保正确命名:
// Person.h
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
- (id)initWithName:(NSString *)name;
- (void)sayHello;
@end
// Person.m
@implementation Person
- (id)initWithName:(NSString *)name {
self = [super init];
if (self) {
self.name = name;
}
return self;
}
- (void)sayHello {
NSLog(@"Hello World!");
}
@end
// main.m
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person* p1 = [[Person alloc]initWithName:@"John"];
[p1 sayHello];
}
return 0;
}
现在,我们定义了一个命名正确的init方法,代码将不再出现ARC语义问题-没有已知的选择器实例方法的错误。
上一篇:ARC下,使用__weak关键字修饰的对象是否会自动置为nil?如果不会,那么释放该对象会发生什么情况?
下一篇:ARC语义问题(Xcode):没有已知的选择器“mapIDWithIdentifier:”的类方法 - XCode 15和Flutter