ios - Concern about memory when choosing between notification vs callback closure for network calls? -
many posts seem advise against notifications when trying synchronize functions, there other posts caution against closure callbacks because of potential inadvertently retain objects , cause memory issues.
assume inside custom view controller function, foo
, uses bar
class data server.
class customviewcontroller : uiviewcontroller { function foo() { // other stuff // use bar data server bar.getserverdata() } }
option 1: define getserverdata
accept callback. define callback closure inside customviewcontroller
.
option 2: use nsnotifications
instead of callback. inside of getserverdata
, post nsnotification
when server returns data, , ensure customviewcontroller
registered notification.
option 1 seems desirable reasons people caution against nsnotification
(e.g., compiler checks, traceability), doesn't using callback create potential issue customviewcontroller
unnecessarily retained , therefore potentially creating memory issues?
if so, right way mitigate risk using callback, not using closure? in other words, define function inside customviewcontroller
signature matching getserverdata
callback, , pass pointer function getserverdata
?
i'm going option 1 need remember of using [weak self]
or whatever need 'weakify' in order avoid memory problems.
real world example:
filterrepository.getfiltersfortype(filtertype) { [weak self] (categories) in guard let strongself = self, categories = categories else { return } strongself.datasource = categories strongself.filtereddatasource = strongself.datasource strongself.tableview?.reloaddata() }
so in example can see pass reference self
completion closure, weak
reference. i'm checking if object still exists - if wasn't released already, using guard
statement , unwrapping weak
value.
definition of network call completion closure:
class func getfiltersfortype(type: filtertype, callback: ([filtercategory]?) -> ()) { connection.getfilterscategories(type.id).response { (json, error) in if let data = json { callback(data.arrayvalue.map { filtercategory(attributes: $0) } ) } else { callback(nil) } } }
Comments
Post a Comment