2013-11-22 32 views
1

我想在GNU運行時上創建一個新的Objective-C根類。以下是我迄今爲止:GNU運行時:class_createInstance返回使得整型指針沒有轉換

了foo.h:

#include <objc/objc.h> 

@interface Foo { 
    Class isa; 
    int bar; 
} 

+ (id) alloc; 
+ (id) newWithBar: (int) bar; 
- (id) initWithBar: (int) bar; 
- (void) p; 
- (void) dispose; 

@end 

foo.m:

#import <foo.h> 
#include <stdio.h> 

@implementation Foo 

+ (id) alloc { 
    return class_createInstance(self, 0); 
} 

+ (id) newWithBar: (int) bar { 
    return [[self alloc] initWithBar: bar]; 
} 

- (id) initWithBar: (int) bar_ { 
    bar = bar_; 
} 

- (void) p { 
    printf ("bar=%d\n", self->bar); 
} 

- (void) dispose { 
    object_dispose(self); 
} 

@end 

和一個小的測試程序,main.m文件:

#import <foo.h> 

int main(int argc, char *argv[]) { 
    Foo *foo = [Foo newWithBar: 3]; 
    [foo p]; 
    [foo dispose]; 
    return 0; 
} 

當我編譯foo.m時,我得到以下警告:

foo.m: In function ‘+[Foo alloc]’: 
foo.m:7:3: warning: return makes pointer from integer without a cast [enabled by default] 

爲什麼?當我深入到頭文件中時,我可以看到class_createInstance返回了id。我在這裏做錯了什麼?

+0

有趣的問題。我熟悉Mac/iOS上的Obj-C運行時,但與GNU版本不太一樣。爲什麼不讓你的對象從'NSObject'防禦?你的'@interface'聲明是不是將超類定義爲'NSObject'?你爲什麼明確地調用'dispose'?你不應該明確地調用'dispose'。 – Holly

回答

1

您需要包含目標C運行時的頭文件。編譯器的默認行爲是假定未聲明的函數返回一個int。

#include <objc-auto.h> 

對不起 - 以上回答是針對OS X/iOS的。對於GNU,您需要包含runtime.h以及objc.h

#include <objc/runtime.h> 
+0

杜。 (facepalm)謝謝。 –

相關問題