实现Objective-C的根类需要什么? [英] What's required to implement root class of Objective-C?

查看:208
本文介绍了实现Objective-C的根类需要什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这个代码:

// main.m
#import <stdio.h>

@interface Test 
+ (void)test;
@end
@implementation Test
+ (void)test
{
    printf("test");
}
@end

int main()
{
    [Test test];
    return  0;
}

使用LLVM / Clang没有任何框架,

with LLVM/Clang without any framework, it doesn't compiled with this error:

Undefined symbols:
  "_objc_msgSend", referenced from:
      _main in main.o
ld: symbol(s) not found
clang: error: linker command failed with exit code 1 (use -v to see invocation)

所以我添加了 libobjc.dylib 。代码编译,但是抛出此运行时异常:

So I added libobjc.dylib. Code compiled, but threw this runtime exception:

objc[13896]: Test: Does not recognize selector forward::
Program received signal:  "EXC_BAD_INSTRUCTION".

#0  0x9932a4b4 in _objc_error
#1  0x9932a4ea in __objc_error
#2  0x993212b6 in _objc_msgForward
#3  0x99321299 in _objc_msgForward
#4  0x99321510 in _class_initialize
#5  0x99328972 in prepareForMethodLookup
#6  0x99329c17 in lookUpMethod
#7  0x99321367 in _class_lookupMethodAndLoadCache
#8  0x99320f13 in objc_msgSend
#9  0x00001ee5 in start

我意识到root类需要一些实现,但是我不知道接下来该做什么。创建新的根类需要什么?而且是对此有任何规范?

I realized some implementation required for root class, but I don't know what should I do next. What's required to make a new root class? And is there any specification for this?

推荐答案

我刚来到这个问题,因为我有同样的学院派的问题。通过它一点工作后,我发现,这个问题的其他答案是不完全正确的。

I just came to this question because I had the same "academic" question. After working through it a bit, I have found that the other answers to this question aren't completely correct.

这是真的, C 2.0 runtime ,您必须实现某些方法为了您的代码工作。实际上只有一个方法需要实现:类方法 initialize

It is true that on the Apple Objective-C 2.0 runtime, you must implement certain methods in order for your code to work. There is actually only one method that you need to implement: the class method initialize.

@interface MyBase 
+ (void)test;
@end
@implementation MyBase
+ (void)initialize {}
+ (void)test {
 // whatever
}
@end

运行时会自动调用 initialize 当你第一次使用你的类(如解释的在苹果的文档)。不执行此方法的消息转发错误的原因。

The runtime will automatically call initialize when you first use your class (as explained in Apple's documentation). Not implementing this method is the reason for the message forwarding error.

铛test.m -Wall -lobjc (或gcc)将允许你调用类方法测试没有任何问题。使对象分配工作是一个不同的故事。如果你使用实例变量,你至少需要一个 isa 指针。运行时期望这是在那里。

Compiling with clang test.m -Wall -lobjc (or gcc) will allow you to call the class method test without any issue. Making object allocation work is a different story. At the very least, you'll need an isa pointer on your base class if you're using instance variables. The runtime expects this to be there.

这篇关于实现Objective-C的根类需要什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆