iOS Cross Cutting Concerns

306 Views Asked by At

I have a Swift application i'm working on that allows a user to save various settings about their profile. Throughout my code, there are times where knowing these settings/preferences are important for the application's business logic. One of them is where the user works (their job, (which is a row in a sqllite database that has an ID as a primary key). The user is allowed to select one (and only one) in the app at any given time. Think of it like a profile - they can work many jobs, but only have one selected.

The following are scenarios where knowing the workplaceid profile is important:

  1. In my sqllite database, retrieving work/shift information based upon the currently selected work ID(so not the ID from the database, but the ID they currently have selected). I'm passing this into my query.
  2. In an NSDate extension function, when I go to determine some things about their starting date, I need to retrieve their currently selected profile, and use that for the calculation.
  3. Within a particular view model when I want to show/hide certain fields.
  4. On an alert view to show something related to their current workplace.

Now I think the quick and dirty way to do this is simply create a wrapper class to your nsuserdefaults in a utility class. Sure, all your info is stored in sqllite, but your currently selected app preferences are in nsuserdefaults since I can change this around (and it will change). This would parallel my other cross-cutting concerns such as logging/error handling, where I could use similar utility classes for all my work.

The fact that I might call this helper/utility class from every single layer of my application seems like a typical red flag you wouldn't do. Whether it's logging, or a user service to get information.

I'm curious to know what other people are doing in scenarios like this. When you need nsuserdefaults from all over your app, is the answer "eh who cares, just make a utility class and call it wherever you need it" ? Or is there a best practice others have followed with well-designed iOS apps? I know AOP is something folks tend to recommend. Does that have a place in iOS?

Thanks so much stackoverflow :)

1

There are 1 best solutions below

0
On

The user is allowed to select one (and only one) in the app at any given time.

This tells me you want to create a singleton class. Every time you want to change the profile, you hit the singleton class and set it. That class encapsulates all the logic to get/set whatever you need, and the accessor functions. That's what I've been doing in my ObjC code for many years, and it has served me well. It's extremely easy to debug, and the rest of the code needs to know nothing about profile management (unless it's the UI part where you choose a profile).