swift - update viewcontroller from appdelegate - best practice? -
i playing around ibeacons implementing corelocation methods inside appdelegate.swift (methods implemented in appdelegate ensure app background capabilities)
in singleview application comes "viewcontroller.swift", best practice pass data appdelegate viewcontroller update views, uiimages, uilabels or uitableviews ?
i have implemented 2 different approaches:
1) delegation, firing viewcontroller delegation methods inside appdelegate.swift:
protocol beaconlocationdelegate { func minorbeaconchanged(minorvalue:nsnumber) } var locationdelegate: beaconlocationdelegate locationdelegate?.minorbeaconchanged(nearestbeacon.minor)
viewcontroller.swift:
in viewdidload method:
(uiapplication.sharedapplication().delegate appdelegate).locationdelegate = self
(i find rather ugly - better way declare property delegate?)
protocol implementation:
func minorbeaconchanged(minorvalue: nsnumber) { // fancy stuff here }
2) creating reference viewcontroller inside appdelegate:
let viewcontroller:viewcontroller = window!.rootviewcontroller viewcontroller viewcontroller.dosomethingfancy()
both approaches work fine me, think first approach via delegation more elegant , better choice once have multiple viewcontrollers.
any recommendations?
i think second solution easier. ensures view controller not go out of memory (is "released") , app delegate not try contact inexistent object.
also, not understand delegate argument in case of more 1 controllers. in case, have have multiple delegates, not ideal situation. or have change delegate different view controllers outside - not elegant , quite risky.
for multiple view controller scenario recommend notifications via nsnotificationcenter
. lose coupling ensures objects need react receive message. view controllers should start listening notifications upon creation , deregister notification center when disappear.
Comments
Post a Comment