创建一个宏以执行默认初始化 [英] Creating a macro to perform default init
问题描述
我有很多重复此简单样板的方法:
I have a lot of methods that repeat this simple boilerplate:
- (id)myObject {
if(!_myObject) {
self.myObject = [_myObject.class new];
}
return _myObject;
}
所以我想用一个简单的宏替换它:
So I want to replace this with a simple macro:
#define default_init(instance) \
if(!instance) instance = [instance.class new]; \
return instance;
这样我只需要打电话:
- (id)myObject {
default_init(_myObject);
}
上面的代码当前可以编译,但是问题是宏直接设置实例变量的值.相反,我想称呼self.instance = value;
The above code currently compiles, but the issue is that the macro directly sets the instance variable's value. Instead, I'd like to call self.instance = value;
所以不是
if(!instance) instance = [instance.class new];
我想要类似的东西
if(!instance) self.instance = [instance.class new];
但是显然,当前代码不允许这样做.我该如何完成这样的事情?
But obviously the current code does not allow for this. How might I accomplish something like this?
推荐答案
使用此宏:
#define default_init(class, instance) \
if ( ! _##instance ) { \
self.instance = [class new] ; \
} \
return _##instance
我能够创建此实例方法:
I was able to create this instance method:
- (NSMutableArray*) myObject {
default_init(NSMutableArray, myObject) ;
}
我必须添加一个定义类的参数,因为_myObject
仍然是nil
,因此_myObject.class
是nil
.
I had to add a parameter defining the class, because _myObject
is still nil
, therefore _myObject.class
is nil
.
This StackOverflow question and this Cprogramming page recommend wrapping your multi-line macro in do {...} while(0)
:
#define default_init(class, instance) \
do { \
if ( ! _##instance ) { \
self.instance = [class new] ; \
} \
return _##instance ; \
} while(0)
如果确实愿意,可以创建一个定义整个方法的宏:
If you really wanted to, you could make a macro that defines the entire method:
#define default_getter(class, instance) \
- (class*) instance { \
if ( ! _##instance ) { \
self.instance = [class new] ; \
} \
return _##instance ; \
}
然后使用它:
default_getter(NSMutableArray, myObject)
这篇关于创建一个宏以执行默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!