Laurence Wingo
Laurence Wingo

Reputation: 3952

How are these lines of swift code different?

let fakeDataSource = FakeDataSource()

tableView?.dataSource = fakeDataSource

versus just invoking it directly with:

tableView?.dataSource = FakeDataSource()

The second example crashes with an NSException but the first example compiles and works. I'm having trouble seeing the difference. If you need more code pasted please let me know.

Upvotes: 0

Views: 45

Answers (1)

rmaddy
rmaddy

Reputation: 318924

Both are a problem but the first may work better, briefly.

UITableView dataSource is a weak property. So unless something else has a strong reference to the data source object, the data source will become nil.

In the first set of code, the FakeDataSource instance is being held onto by the fakeDataSource variable. So the FakeDataSource instance will survive until the fakeDataSource variable goes out of scope.

In the second set of code, the FakeDataSource is created and assigned in one line. After that line, there is no longer any strong reference to the FakeDataSource instance so it gets deallocated right there and the dataSource becomes nil nearly immediately.

In both cases, there is a problem. The only difference is the timing of when the FakeDataSource instance gets deallocated.

The fix is the same for both. Keep a strong reference to the FakeDataSource instance. This is typically done by using a property.

Upvotes: 2

Related Questions