考虑以下代码示例:
class SomeArbitrarilyNamedClassPlusPlus {
public:
SomeArbitrarilyNamedClassPlusPlus(NSObject *object) { object_ = object; }
SomeArbitrarilyNamedClassPlusPlus() { object_ = nil; }
private:
NSObject *object_;
};
@interface SomeArbitrarilyNamedClassObjective : NSObject
{
SomeArbitrarilyNamedClassPlusPlus *_plusPlusObject;
}
@end
@implementation SomeArbitrarilyNamedClassObjective
-(id)init
{
if ((self = [super init]))
{
_plusPlusObject = new SomeArbitrarilyNamedClassPlusPlus(self);
}
return self;
}
-(void)dealloc
{
NSLog(@"deallocated");
delete _plusPlusObject;
}
@end
int main(int argc, const char * argv[])
{
{
SomeArbitrarilyNamedClassObjective *object = [[SomeArbitrarilyNamedClassObjective alloc] init];
}
return 0;
}
object
变量永远不会被释放。您可以使用Instruments进行检查-额外的保留计数器增量发生在-(id)init
调用中。
我从来没有想过C++类中的属性是强的,这让我想知道——有没有办法让指向Objective-C对象的C++属性变得弱?
更新:有一种方法可以避免这种情况,使用C++类中指向void
的指针而不是NSObject*
,并在-(id)init
方法中初始化C++类,如下所示:
...
_plusPlusObject = new SomeArbitrarilyNamedClassPlusPlus((__bridge void*)self);
...
然而,问题仍然存在——是否有一种方法可以将Objective-C类型保存在C++类中,但使它们变弱?
答案很简单——在C++类中使用__weak
属性:
class SomeArbitrarilyNamedClassPlusPlus {
public:
SomeArbitrarilyNamedClassPlusPlus(NSObject* object) { object_ = object; }
SomeArbitrarilyNamedClassPlusPlus() { object_ = nil; }
private:
__weak NSObject* object_;
};