Is it ever Ok to have a 'strong' reference for a delegate?

前端 未结 4 523
Happy的楠姐
Happy的楠姐 2020-12-04 20:32

I have a class that retrieves JSON from a URL and returns the data via the protocol/delegate pattern.

MRDelegateClass.h

#import 

        
4条回答
  •  庸人自扰
    2020-12-04 21:04

    As other said it's about architecture. But I'll walk you through it with several examples:

    Retry upon failure

    Suppose you've made a URLSession, and are waiting for a network call you made through a viewController, sometimes it doesn't matter if it failed, but at other times it does. e.g. you're app is sending a message to another user, then you close that viewcontroller and somehow that network request fails. Do you want it to retry again? If so then that viewController has to remain in memory, so it can resubmit the request again.

    Writing to disk

    Another case would be when a request succeeds you may want to write something to the disk, so even after the viewcontroller has its UI updated you might still want to sync your local database with the server.

    Large background tasks

    The original use case for NSURLSession was to power background network task execution, large file downloads and things of that nature. You need something in memory to handle the finalization of those tasks to indicate execution is complete and the OS can sleep the app.

    Associating the lifecycle of downloading large files to a certain view is a bad idea…it needs to be tied to some more stable/persistent e.g. the session itself…

    Normally if I’m going to use the delegate based system rather than URLSession’s newer block-based API, I have a helper object that encapsulates all the logic necessary to handle failure and success cases that I may require that way, I don’t have to rely on a heavy VC to do the dirty works


    This is answer was entirely written thanks to a conversation I had with MattS

提交回复
热议问题