user2530191 user2530191 - 2 months ago 29
iOS Question

"attempted to retain deallocated object" in circular reference

I have a program that tracks precious metals prices.

A TransactionDTO has an unowned reference to an AssetDTO

AssetDTO Snippet:

public class AssetDTO: Equatable {
var name: String!
var transactions = [TransactionDTO]()


TransactionDTO Snippet:

unowned var asset: AssetDTO

init(asset:AssetDTO, type:Constants.TransactionType) {
self.asset = asset
self.type = type
self.date = Date()
}


In a UI controller class, I iterate over the transactions in a table, and show the related metal (gold, silver, etc). In my viewDidLoad, to demonstrate the error, i have the following code

var txs = [TransactionDTO]()
for asset in assetManager.findAllMetals() {
for tx in asset.transactions {
txs.append(tx)
print("the asset name for this is \(tx.asset.name)")
}
}

for tx in txs {
print("the asset name for this is \(tx.asset.name)")
}


In the first loop, the name of the asset prints, in the second loop, i get:

libswiftCore.dylib`_swift_abortRetainUnowned:
0x108d44cc0 <+0>: leaq 0x3058b(%rip), %rax ; "attempted to retain deallocated object"
0x108d44cc7 <+7>: movq %rax, 0x95f0a(%rip) ; gCRAnnotations + 8
0x108d44cce <+14>: int3 -> 0x108d44ccf <+15>: nop


Any ideas??

Answer

Remove unowned from

    unowned var asset: AssetDTO

unowned is effectively like weak, and presumably nothing else is referencing the asset, so it gets deallocated. However, unlike weak, unowned does not nil out the variable for you. Hence the error you're getting. If you change it to weak, you will probably find it is becoming nil.

What are you trying to achieve with unowned?

Comments