Choosing a singleton or category?

Pretty early in my application, when I was much less experienced than now, I would like to animate some transitions between view controllers using my own custom animations. Having no idea where to start, I looked around SO for a template similar to MVC, which could be accessed from almost any controller at any time, and, as it turned out, a one-way way.

What I did not understand is that there seems to be a strong and well-protected hatred of the singleton pattern, and I myself begin to understand why, but this is not relevant.

So, after some time, I decided to transfer my same implementation to a category in the UINavigationController (in the end, it handles transitions!), Saved the original classes for comparison, and I wonder which method will work best. Having fully tested both versions, I can say without any doubt that they are equal in all respects, including speed, accuracy, smoothness, frame rate, memory usage, etc. So, which one is "better" in terms of general maintainability?

EDIT: after reading the well-written arguments that you all did, I decided to use singleton. @JustinXXVII made the most convincing argument (IMHO), although I find every answer here equally worthy of attention. Thanks to everyone for your opinion, I supported all the answers in the question.

+5
source share
6 answers

I will make a case for a single object. Singletones are used in all cases UIKitand iOS. One thing you cannot do with categories is to add instance variables. There are two things in this:

  • MVC workflows do not migrate objects with intimate knowledge of other objects.
  • Sometimes you just need a place to refer to an object that doesn’t actually belong anywhere.

These things contradict each other, but the added ability to save an instance variable that really doesn't have an β€œowner” is the reason I prefer singleton.

XCode, "" , AppDelegate.

/ /. , UIViewController . , .

NSUserDefaults, , [[NSUserDefaults standardUserDefaults]stringForKey:@"blah"], , .

. , , , , . ( AppDelegate)

+3

, .

, UINavigationController, , , : (after all, it handles transitions!)

, , , , , , ?

, singleton, factory , . , , , , , , .

+6

, "" ( , ), , , :

  • singleton , , . , . ( )

  • - , a. ( ! ok... )

, , - UINavigationController. UINavigationController, - , ( , addubviews ..), ( , ), , , , .

, , , , , , , , , . singleton (... , n, n + 1).

+3

, Singleton, . , .

, , . , -, . , - , .

, , , , , , . , , .

, , . () .

, , , . . Singeltons - ( , ). , .

; .

* , .

+2

UIViewController ? .

+2

, , , . :

+ (MyClass*) sharedInstance
{
    static MyClass *instance = nil;
    if (instance == nil)  instance = [[MyClass alloc] init];
    return instance;
}

, , , , accessor: , . UIApplication, .

, singleton. , , , , . , , , , () . , Objective C, , . , , .

: / ( , ), . ++ - BaseTransition . C (, , , , ), , . , , , .

+1

All Articles