iOS-报错“No visible @interface for ‘NSObject‘ declares the selector ‘XXXX:‘”
Posted MinggeQingchun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS-报错“No visible @interface for ‘NSObject‘ declares the selector ‘XXXX:‘”相关的知识,希望对你有一定的参考价值。
这个错误一般是NSObject对象不符合某种协议,不能调用某个方法
最常见的就是NSCopying协议 ,NSMutableCopying协议,NScoding协议等
1、如NSObject不符合NSCopying协议,如果在NSObject或者直接继承NSObject的子类实现了NSCopying协议,且实现了- (id)copyWithZone:(nullable NSZone *)zone方法,代码如下:
//People.h文件
@interface People : NSObject<NSCopying>
@property (nonatomic, copy)NSString *name;
@end
//People.m文件
@implementation People
- (id)copyWithZone:(nullable NSZone *)zone {
People *people = [super copyWithZone:zone];
people.name = self.name;
return self;
}
@end
调用[super copyWithZone:zone],这时就会报错:
No visible @interface for 'NSObject' declares the selector 'copyWithZone:'
原因:
NSObject不符合NSCopying协议,因此不能调用[super copyWithZone:zone]
解决方案:
调用[[[self class] allocWithZone:zone] init]
如下:
@implementation People
- (id)copyWithZone:(nullable NSZone *)zone {
People *people = [[[self class] allocWithZone:zone] init];
people.name = self.name;
return self;
}
@end
2、NSObject实现NSMutableCopying协议同理,在- (id)mutableCopyWithZone:(nullable NSZone *)zone中
不能调用[super mutableCopyWithZone:zone],需要调用[[[self class] allocWithZone:zone] init]
3、NSObject实现NScoding协议
我们在 解档方法 - (instancetype)initWithCoder:(NSCoder *)coder
// 解档方法
- (instancetype)initWithCoder:(NSCoder *)coder {
if (self == [super initWithCoder:coder]/*[super init]*/) {
//释放内存!
free(ivars);
}
return self;
}
如果调用[super initWithCoder:coder] 就会报错:
No visible @interface for 'NSObject' declares the selector 'initWithCoder:'
也是因为NSObject不符合NScoding协议,我们调用[super init]方法即可
// 解档方法
- (instancetype)initWithCoder:(NSCoder *)coder {
if (self == [super init]) {
//释放内存!
free(ivars);
}
return self;
}
以上是关于iOS-报错“No visible @interface for ‘NSObject‘ declares the selector ‘XXXX:‘”的主要内容,如果未能解决你的问题,请参考以下文章
iOS报错 -pie can only be used when targeting iOS 4.2 or later