Thursday 15 January 2015

swift: best class design with closures to avoid strong reference cycles -



swift: best class design with closures to avoid strong reference cycles -

suppose have 2 classes. first class has bunch of little functions typically used in combination each other. because these functions need access shared resource, it's more efficient grouping them together.

to phone call little functions, need reference class. there 2 ways this.

class firstclass { // lots of little functions ... func dowork(){} //group function takes closure func transactionsa(workunit : ()->(nserror?)) -> nserror? { //obtain access shared resource ... //do work workunit() //close access shared resource ... } func transactionsb(workunit : (let instanceoffirstclass)->(nserror?)) -> nserror? { //obtain access shared resource ... //do work workunit(self) //close access shared resource ... } } class secondclass { allow instanceoffirstclass = firstclass() //first approach func dogroupworka() { instanceoffirstclass.transactionsa() {[unowned self] () -> (error?) in self.instanceoffirstclass.dowork() } } //second approach func dogroupworka() { instanceoffirstclass.transactionsb() {[unowned self] (let instanceoffirstclass) -> (error?) in //do actual work via smaller functions instanceoffirstclass.dowork() } } }

in first approach phone call functions via self.instanceoffirstclass, in sec approach obtain instance parameter of closure.

there not much difference approach better? there risk of creating reference cycles?

my concrete utilize case little sqlite wrapper.

edit: expand upon particular utilize case, although think question , reply should broader that:

firstclass sqlite wrapper. talks straight database (open/close connection, create/prepare/bind sql queries fetch , insert).

secondclass can class needs store or retrieve data. take advantage of transactions, need grouping queries. dowork() begin transaction, loop(fetch, process, insert), commit/end transaction.

the transaction functions open , close database connection when appropriate. avoids connection remains open idle entire duration of application or lifetime of document.

should error occur, transaction rolled , connection closed.

design-patterns swift

No comments:

Post a Comment