我在Objective-C中偶然发现了一些奇怪的行为.我有一个main.m:
#include <Foundation/Foundation.h>
#include "AClass.h"
int main(int argc, char* argv[]) {
AClass* tmpClass = [[AClass alloc] init];
[tmpClass setAVariable:12];
return -1;
}
Run Code Online (Sandbox Code Playgroud)
标题AClass.h:
#include <Foundation/Foundation.h>
@interface AClass: NSObject;
-(void) setAVariable:(int) bVariable;
@property int aVariable;
@end
Run Code Online (Sandbox Code Playgroud)
和相应的实现文件AClass.m:
#include <Foundation/Foundation.h>
#include <AClass.h>
@implementation AClass
@dynamic aVariable;
int aVariable;
-(void) setAVariable:(int)bVariable {
NSLog(@"foo:");
self.aVariable = bVariable;
}
@end
Run Code Online (Sandbox Code Playgroud)
在Linux上使用clang或在OSX上使用Xcode编译此代码时,setAVariable:会触发无限递归.我想知道这是否是clang/Objective-C中的错误.
我有一个带有静态函数getSharedInstance的类,因此应该给我一个指向已经实例化的类的指针.
标题:
class foo {
public:
static foo *getSharedInstance();
private:
static foo *sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
执行:
foo *foo::getSharedInstance() {
if(sharedInstance == NULL)
sharedInstance = new foo();
return sharedInstance;
}
Run Code Online (Sandbox Code Playgroud)
我不明白的一点是,为什么我得到对变量sharedInstance的未定义引用?