0

考虑这个代码示例:

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++ 属性变弱?

更新: 有一种方法可以避免这种情况,使用指向voidC++ 类的指针,而不是像这样NSObject*在方法中初始化 C++ 类-(id)init

    ...
    _plusPlusObject = new SomeArbitrarilyNamedClassPlusPlus((__bridge void*)self);
    ...

然而,问题仍然存在——有没有办法在 C++ 类中保存 Objective-C 类型但使它们变弱?

4

1 回答 1

2

好吧,答案很简单——__weak在 C++ 类中使用属​​性:

class SomeArbitrarilyNamedClassPlusPlus {
public:
    SomeArbitrarilyNamedClassPlusPlus(NSObject* object) { object_ = object; }
    SomeArbitrarilyNamedClassPlusPlus() { object_ = nil; }

private:
    __weak NSObject* object_;
};
于 2014-10-01T22:06:58.653 回答