0

Consider this code example:

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;
}

The object variable never gets deallocated. You can check it with Instruments - additional retain counter increment happens inside the -(id)init call.

I would never expect that attributes in C++ classes are strong and this makes me wondering - is there a way to make c++ attributes pointing on Objective-C objects weak?

UPDATE: There is a way to avoid this using pointers to void in C++ class instead of NSObject* and initialize C++ class in -(id)init method like that:

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

However, the question still remains - is there a way to save Objective-C types inside C++ classes but make them weak?

peetonn
  • 2,942
  • 4
  • 32
  • 49

1 Answers1

2

Well, the answer turned out to be quite straightforward - use __weak attribute in C++ class:

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

private:
    __weak NSObject* object_;
};
peetonn
  • 2,942
  • 4
  • 32
  • 49