Proper way to pull JSON API response and store or

2019-09-15 05:34发布

问题:

I'm interested in knowing if there's a "proper" way to handle JSON responses from API requests.

Right now I have a struct that contains a static var. In the AppDelegate I grab the JSON from a URL (using Alamofire). I am able to reference it later in different views, however I have read that there are better ways than a "struct hack" to handle this.

My goal is to minimize the amount of calls, and only refresh when it's appropriate (ie. user "pulls down to refresh", "new object inserted into database", etc). Should this be how I handle it, or should I load different JSON responses on each new view, depending on what's required?

Any direction is appreciated.


Edit: Here's where I read that Structs were a "hack" for a "global variable". Maybe storing JSON in a struct is different than keeping a typical user variable in one. I don't know. See the second Answer's remarks.

Global Variables in Swift

As for the Struct I have:

In my jsonDataHolder.swift file:

struct jsonDataHolder {
    static var jsonData:AnyObject = []
}

In my AppDelegate.swift file, I have the following in DidFinishLaunchingWithOptions section:

Alamofire.request(.GET, "http://xxxxxxxxxx.com/yyy", encoding: .JSON).responseJSON { (_, _, JSONData, _) in
    jsonDataHolder.jsonData = JSONData!
}

Again, this all works fine. Just not sure if it's the "right" (if there is such a thing) way to do it.

回答1:

If I understand the question correctly, though, this seems like the oft debated "singletons are evil" discussion. As we are supposed to avoid debating opinions here on Stack Overflow, I'll simply refer you to What is so bad about singletons?.

I must confess, though, that what I find more troubling is the the lack of any clear interface for this JSON structure. I'd rather see a model object with some logical public interface.

With this current object, your entire app (or at least everything that interfaces with this object) is dependent upon the private implementation details of the JSON.


The advice to avoid singleton-style patterns should not be accepted as dogma, but you should consider the reasons why that advice is generally offered (complicates testing, results in inappropriately tightly-coupled code, etc.). If you're adopting pattern like AnyObject that obscures implementation-dependent JSON structure, then there's no point in worrying about the singleton pattern, because you've already baked all of these limitations/problems in your code already.