我决定更好地理解 Objective-C 中类的工作并编写一个简单的基类,但我遇到了以下问题:尝试调用继承自 Written 类的对象上的方法会导致段错误,而如果继承自 NSObject没有问题。目前尚不完全清楚基类如何影响后代中的调用方法和访问字段。
#include <objc/runtime.h>
#import <Foundation/Foundation.h>
__attribute__((objc_root_class))
@interface TestRoot
+alloc;
-(instancetype)init;
@end
@implementation TestRoot
+alloc {
return class_createInstance(self, 0);
}
-(instancetype)init {
return self;
}
@end
@interface FromNSObject : NSObject
@property(readwrite) int num;
@end
@implementation FromNSObject
-(instancetype)init {
self = [super init];
_num = 5;
return self;
}
-(void)print {
printf("%d\n", _num);
}
@end
@interface FromTestRoot : TestRoot
@property(readwrite) int num;
@end
@implementation FromTestRoot
-(instancetype)init {
self = [super init];
_num = 5;
return self;
}
-(void)print {
printf("%d\n", _num);
}
@end
int main(int argc, char const **argv) {
FromNSObject *ns = [[FromNSObject alloc] init];
[ns print]; // 5
FromTestRoot *ts = [[FromTestRoot alloc] init];
[ts print]; // segmentation fault
return 0;
}