Home > Software engineering >  Do I need to manually free swift instance which is referred in objective-c
Do I need to manually free swift instance which is referred in objective-c

Time:10-20

I have CBPeripheral extension written in objective-c, and a variable bleManagerStore refers to BleManagerStore instance. When the CBPeripheral instance auto-released, will the reference count to bleManagerStore automatically decreased too? If not, how do I solve it?

I have the same question with the variable currentSeq too.

Thanks.

objective-c code

@implementation CBPeripheral(com_megster_ble_extension)
BleManagerStore *bleManagerStore;
NSNumber *currentSeq;

-(void)setBleManagerStore:(BleManagerStore*) store {
    bleManagerStore = store;
}

-(BleManagerStore*)getBleManagerStore {
    return bleManagerStore;
}
-(void) setSeq:(NSNumber*) seq {
  currentSeq = seq;
}

@end

Swift code

class BleManager {
    var peripheral: CBPeripheral?
    func test() {
        peripheral?.setBleManagerStore(BleManagerStore())
        peripheral?.setSeq(NSNumber(value: 12))
    }
}

CodePudding user response:

No. Swift handles memory automatically using Automatic Reference Counting. Which automatically frees up memory from class instances that don't require it anymore.

However, Reference counting only works with instances of classes, as mentioned in the swift language guide

Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and aren’t stored and passed by reference.

  • Related