I've been wondering in what cases it is really necessary to adopt the singleton pattern in objective-C (e.g., define a dedicated class and create a single instance), that using the class as an object won't do.
Particularly, I'm thinking of the following solution:
Define and use appropriate class methods, instead of instance methods on the singleton instance;
Use static variables (file-scope globals), instead of instance variables of the singleton instance;
Use the class object when registering as an observer for notifications, instead of the singleton instance. Although the class object is an objective-C object in its own right (right?), this would require that the notification handler registered be a class method; (is this possible?)
For example, instead of having a Texture class (model object) and a TextureManager singleton (resource manager), you could have all texture creation/cleanup implemented as class methods and static variables of the same Texture class (factory pattern plus some resource management).
Any thoughts on this design?
EDIT:
Now that I think of it, and still in the Texture example above, even if I keep the two classes separate (Texture and TextureManager) I must choose between A. Having the manager be a singleton, and operate it with instance methods, or B. Having the manager be an instanceless, auxiliary class. To clarify:
Texture* myTexture = [[TextureManager defaultManager] textureWithName:#"TextureName"];
// (singleton, client uses instance methods)
versus
Texture* myTexture = [TextureManager textureWithName:#"TextureName"];
// (Class standing in for singleton, client uses class methods)
The latter looks more straightforward and less cumbersome/verbose, but I wonder which design is "more correct". Of course, the former allows for more than one TextureManager instance shall the need arise (not in my case).
I have been thinking about the same thing and I think I have an answer for you.
It depends on what you need to do with it. Neither is necessarily more "correct".
Read on if you want the details of how I came to my conclusion or scroll down to the tl;dr section.
As you said, it would appear (externally) less cumbersome to access the singleton to have the class manage the singleton for you. Essentially you would do this by replacing the singleton's factory method with an initializer method. Looking at Apple's documentation on this you can see where they show a "shared" method that acts as the factory to produce the singleton upon demand.
static MyGizmoClass *sharedGizmoManager = nil;
+ (MyGizmoClass*)sharedManager
{
if (sharedGizmoManager == nil) {
sharedGizmoManager = [[super allocWithZone:NULL] init];
}
return sharedGizmoManager;
}
Instead of doing this you could replace the method with a void initializer like so:
+ (void)initializeMyGizmo
{
if (sharedGizmoManager == nil) {
sharedGizmoManager = [[super allocWithZone:NULL] init];
}
// whatever else needs to be done to the singleton to initialize it
}
and then ONLY ever use class methods and allow the MyGizmoClass to manage updates to the singleton like [MyGizmoClass setGizmoName:#"Gadget"].
NOTE: In this scenario it would be confusing to someone looking at the .h file to see properties, in which case they may come to the conclusion that they should create an instance of the object themselves, or be able to have access to the singleton in some form or fashion. So if you were to go the route of encapsulating access to the singleton it would not be wise to use public variables.
To that point:
If you do limit access to solely through the class itself you lose any getters and setters or other free things that come along with properties. This means that if MyGizmoClass were to have as part of it's model an NSString *gizmoName you would be forced to create custom getters and setters for this "property" and keep it either as an ivar or property in an interface extension in the .m file (i.e. private) of the singleton class, or as an adjacent static variable.
So this begs the question (and is what got me pondering in the first place), should we even include the line static MyGizmoClass *sharedGizmoManager = nil; at all or can we nix the internal interface extension altogether and replace any possible ivars or properties that we want to limit access to with static implementations in the implementation?
I answered that already...
It depends on what you need to do with it.
tl;dr
First Scenario
If you ever (even the slightest chance) need to subclass your
TextureManager or could create multiple instances of it (making it
no longer a singleton) it would be better to stick to the regular
Apple convention for a singleton.
This includes multiple "singletons" wherein you might have several
TextureManagers preconfigured with different settings.
In this case you would use properties as you need them (publicly or
privately) as well as ivars. You could also use a mix of ivars and
statics but you would still always need to have a static instance of
your TextureManager inside of the TextureManager implementation.
Second Scenario
If you ONLY will ever need ONE instance of the TextureManager and it will run completely standalone with no intermixing further down the line then you could completely remove the static instance of your class within the implementation in the .m file and replace ivars and properties with static variables within that implementation.
This can be useful if you are storing off properties or settings in CoreData and only need them for configuration.
Just remember in this case you will have to create all getters and setters for the static variables and will only be able to access them using class methods (but that's sorta the point).
Other Interesting Stuff
This answer offers an interesting solution to the question of when and how to call the "initializer" method or create the singleton. This can be used with each scenario to either initialize the singleton in the first scenario, or preload defaults into the class-level statics in the second scenario.
If you want to stick with a static singleton in the implementation you might look at this article to give you a better idea at the true "global scope" of your singleton.
Yes you can definitely make a Texture class without needing a singleton.
Singletons probably should not be created and used as an object.
Singletons can be used for many important things.
I certainly don't know all of the things they can be used for, but i will tell you what i have used them for in the past.
I usually use singletons for level navigation in a game with many levels (like Angry Birds).
By level navigation, i mean... when a player completes a certain level in a game i simply call a class method on the singleton and pass in the level number, then the singleton's class method figures out which level is next (if user presses 'next level' button).
I can help you understand the Singleton class better and when it applies.
Pattern : Singleton
Intent : Enforce that a class can only have a single instance, as well as making that instance accessible to any other object.
Motivation : Sometimes we need to make sure that there exists only a single object of a certain type in our problem domain. Example: A student carries around only a single backpack, which he can fill with books. We would not want to relate him to secondary backpack, with even more books.
Use when :
There is need for only a single instance of a class, and that instance must be accessible from different objects within your code.
When you (possibly) need to be able to add more functionality to that class by subclassing it.
Related
The recommended practice is to use property, including private ones through class extension instead of ivar (except in init and dealloc) in the post ARC environment.
Aside from it being a recommended practice, what are the main drawbacks in someone using ivar instead of property? I am trying to convince some folks to make the switch but some have argued ivar works just as well and faster. So I would like to collect good solid arguments rather than giving soft statements such as "it's better, more consistent, etc."
There is no right answer to your question, just opinions. So you'll get varying answers, here's one to add to your collection :-)
Using private properties is is not recommended practice, it is largely a fad. :-)
A public property is part of the encapsulation of the class - how a property (or method) is implemented is not relevant to the user, only the behaviour.
A class does not need to hide how it is implemented from itself!
So the only use cases for private properties is where they provide some behaviour in a convenient way to the implementation of the class, not to hide that behaviour.
A private property with the copy attribute may be convenient if the class is, say, obtaining mutable strings from another class and needs to preserve their current values.
If the class wishes to lazily construct a value if it is needed but keep it after that time then a property can handle that conveniently. Of course a method or function can as well as a property is after all just a method call.
To make the choice think convenience/code design rather than encapsulation as you do for public properties. And most of the time you'll probably just use instance variables, just as you just use local variables.
HTH
There is not much difference in terms of performance. In reality, properties are instance variables with the accessors generated. So the reason why you want to do properties is because the code to generate the KVO notifications and the setter/getter methods are generated to you. So you have less time doing repetitive code on all your classes.
There are a few cases where using a private property is better or required over using an instance variable:
KVO - Since KVO requires getter/setter methods to do the work, you need a property (technically just the methods). Using KVO on a private property probably isn't too common.
Lazy loading or other "business logic" around the value. Using a property with custom setter/getter methods allows you to apply lazy loading and/or other logic/validation around the value.
Access to the value inside a block using a weak reference.
The last point is best covered with an example. As many people know, under certain conditions you can create a reference cycle in a block and this can be broken using a weak reference to self. The problem is that you can't access an ivar using the weak reference so you need a property.
__weak typeof(self) weakSelf = self;
[self.something someReferenceCycleBlock:^{
weakSelf->_someIvar = ... // this gives an error
weakSelf.someProperty = ... // this is fine
}];
Basically, use an ivar if none of these points will ever apply. Use private properties if any of these may apply over the lifetime of the class.
I've started using Xcode's refactoring abilities (edit > refactor > extract) and noticed that Xcode offers to extract a method or a function.
I've read here and elsewhere about the differences between the two and understand that a method is connected to a class while a function is not. So I'm not looking for definitions, please.
Assuming that no arguments are involved, when is it appropriate to use one instead of the other? I understand that if something isn't really about the class then it could be a function but again, that's just about the definitions. I'm looking for good ol' use cases.
In my personal case, I'm trying to refactor some code out of the AppDelegate's applicationDidEnterBackground. As it is the only place to handle events upon entering the background, the only way to clean up the code is to extract subroutines into .. well, functions. But they'd be inside AppDelegate.m so wouldn't they be methods?
Hmmm..
Personally, I only use functions if, and only if, the following two requirements are met:
I use it so frequently within a given class, or throughout the project, that it warrants being generalized.
It has no side-effects or context dependancies (none of that void *context mess).
In my opinion, C-style functions should only be used as a last resort or in cases where you truly need functional behavior within this kind of an application. Event handling is both application-specific, and context sensitive, so it's best if you left that alone and focused on refactoring common patterns out.
You use functions when you have a, well, function ;-) You know the definitions: a method has an implicit argument self and can access instance variables using that; a function has no implicit arguments - everything it needs must be passed in.
If you are refactoring part of a larger method, that part does not access instance variables, and you are not refactoring it so that a subclass can override it, then let Xcode build you a function. When its done add static to it so it is private to the class.
In doing this you've lost nothing and made it clear that the piece of code is a function - it does not alter the state of the object.
There is of course no hard line between picking a function and a method, its a fuzzy boundary. If a piece of code, say, just accesses one or two instance variables but does not update them then you might pick a function - again making it clear that the object state is not being modified. But you don't want to pass lots of instance variables in as parameters, that is just hard to read (and inefficient).
Using functions can be good, and its certainly not bad to do so in Objective-C.
Method of a class usually need to access instance variables connected to that class. Functions in Objective-C are not connected to a class, and therefore have no access to any non-public member variables of classes.
Consider the class KNode, which contains member variable _memberVar.
#interface KNode : NSObject {
int _memberVar;
}
#end
Any method of this class could access and change the member variable, but any old function cannot, as it is private.
#implementation KNode
- (void)modify {
_memberVar = 10;
}
#end
The following function will not work
void modify(KNode * node) {
_memberVar = 10;
}
Two small but meaningful advantages of functions:
They can be internal-only by marking them static, or
__attribute__((visibility("hidden"))), which is helpful for framework developers
They can be inlined. For example, I use this pattern for fast lazy queue creation:
static inline dispatch_queue_t sharedQueue() {
static dispatch_queue_t queue;
static dispatch_once_t once;
dispatch_once(&once, ^{
queue = dispatch_queue_create("foo", 0);
});
return queue;
}
OK, I know this question might seem irrelevant or too basic, but - since I always want to know what I'm doing and why I'm doing it, if it fits my design - please shed some light.
So, here's what I need :
Let's say we've got a class
We want to use its methods from pretty much anywhere
Instead of passing an object around, I decided to go for class methods and pseudo-global instances
So, let's say we've got a class named "MyDocumentManager".
This is what I usually do :
+ (MyDocumentManager*)documentManager
{
MyDocumentManager* newDocumentManager = [[MyDocumentManager alloc] init];
if (newDocumentManager)
{
// initialize that new document manager
}
return newDocumentManager;
}
And then use it like :
[[MyDocumentManager documentManager] someMethod];
However, I usually see people suggesting something like :
+ (MyDocumentManager*)sharedManager
{
static dispatch_once_t pred;
static MyDocumentManager *sharedManager;
dispatch_once(&pred, ^{
sharedManager = [[MyDocumentManager alloc] init];
});
return sharedManager;
}
So, here's my questions :
Is is the same thing?
If not, what is the difference?
What are the pros/cons of its approach? (in terms of memory/speed/etc)
Which one should I use and why?
Do they both fit what I need them for?
Is it the same thing?
No.
If not, what is the difference?
What you have doesn't implement a singleton, since it allocates a new instance of the class upon every function call. It's rather called a factory method. The definition of a singleton is that a certain class method always returns the same instance of the class.
Which one should I use and why?
You should generally avoid using singletons, because it's often considered bad practice, although there are cases when it's handy to have them. For example, if you have a class that uses encapsulated data but you only need quasi class-level methods, then it's better to implement a singleton with properly placed instance variables than implement class methods and tons of global/static variables (this is because in Objective-C, classes can't have member variables, only objects).
Do they both fit what I need them for?
You decide that.
The code you pasted in "what I usually do" is broken. It doesn't return a singleton. It returns a brand new object every time you call it (and if this isn't ARC then it's leaking it too).
The code you pasted as what people suggest is the correct code. Not only does it return a shared object each time, without leaking, but it's also thread-safe (so far as initialization of the object is concerned; it doesn't say anything about whether use of the object is thread-safe).
While recently working with Objective-C and various libraries written in it, I've noticed two really popular singleton patterns. One version fetches the singleton instance and calls its instance methods and other version only exposes class methods and never gives you an instance to work with. All have the purpose of abstracting access to a single resource (StoreKit, CoreData, Parse API etc.). For example, here's the former approach used in MKStoreKit:
// initialize singleton during app boot
[MKStoreManager sharedManager]
// sometime later in the app
[[MKStoreManager sharedManager] buyFeature:kFeatureAId
onComplete:^(NSString* purchasedFeature)
{
NSLog(#"Purchased: %#", purchasedFeature);
}
onCancelled:^
{
NSLog(#"User Cancelled Transaction");
}];
or alternatively NSUserDefaults, UIApplication etc.. The other approach can be seen in MagicalRecord or here with Parse API:
// configure API credentials sometime during app boot
[Parse setApplicationId:#"123456"
clientKey:#"123456"];
// sometime later
PFObject *testObject = [PFObject objectWithClassName:#"TestObject"];
[testObject setObject:#"bar" forKey:#"foo"];
[testObject save];
What are some pros and cons of the two approaches and is one of them fundamentally better than the other?
Not having to retrieve the shared instance saves some screen estate (the performance difference is likely irrelevant), but am I screwing myself in some other way, for example, testability-wise?
Thanks!
There are two different ways to implement the approach based on class methods:
Make a singleton instance using a class hidden from everybody, and hide its methods behind wrapper class methods with identical signatures, or
Make class methods that do all the work
The implications of the first implementation are that everything you can do with a singleton, you can do with the hidden singleton:
using a subclass becomes a possibility
switching the instance in the middle of the run is easy
the state lives in instance variables
initialization follows the familiar pattern
If you go for an implementation that does not use a singleton, you would be relying on static variables to keep your current state. That is a legitimate choice, but the initialization pattern becomes different (perhaps even using a dispatch_once), you cannot switch the implementation in the middle without relying on some ugly if conditions, and using a subclass becomes a lot more tricky.
Testing the first implementation is somewhat easier than testing the second one, because you can provide a separate implementation of the singleton for testing, perhaps through the back door; with a static-based implementation, this route cannot be taken.
To summarize, I would use a singleton-based solution, with the singleton optionally hidden behind a "facade" that provides access to singleton's methods. I would not use an implementation where all state must be placed in static variables.
One advantage of the singleton approach is that it becomes trivial to allow other instances if you need to. If you take the class method approach, that's all you get without a lot of refactoring.
I went through the source code of GNUStep's NSNumber's implementation to understand how does factory method implementation works there.
From there What I could understand was we have NSNumber with blank implementation for all initWithXYZ kind of methods. and NSTemporaryNumber was acting like an intermediate class in the hierarchy that implemented all the initWithXYZ methods where it actually created objects of specific types , autoreleased itself and returned the created object.
Also allocWithZone was overridden to avoid creation of NSNumber object and to create object of NSTemporaryNumber if it was so otherwise create objects of specific types.
What I didn't understand was, can't the same things be done by NSNumber itself ?
why give blank implementations at all , create the object of specific type and then autorelease self.
Also if we have implementations of createXYZ methods in NSNumber itself, why have initWithXYZ methods ?
If I have to implement a factory implementation for my project where say I have two mediaItems, video , audio and photo etc.
for which I have separate classes and corresponding enums which I pass to initWithMediaType who will create an object of correct child class, return it and destroy itself.
Have two classes like NSNumber and NSTemporaryNumber: say Media and TemporaryMedia, one with blank implementations other with implementations as mentioned above ?
Should I do something like this ?
Is this the way we have to implement Factory pattern in Objective C ?
My question might seem silly biut I come from a Java, C++ background where things looked different.
The purpose might be the same but I am finding it difficult to understand the way Objective C does it since it does not have abstract classes.
Link to the source:
http://www.koders.com/objectivec/fid46956186C20201706AFE1744AA7AFEEE09D1FE5A.aspx
The point is that NSNumber is a class cluster. The class you actually end up with may be an NSIntNumber, an NSFloatNumber or one of several others. They all respond to the same messages as NSNumber (and, usually in this pattern will be subclasses of it, but that isn't required) so it makes no real difference to the caller.
When you call alloc there's no way to know what sort of object to create, so a neutral type is created and returned instead. It substitutes appropriately upon receiving an appropriate init.
So this pattern is for the implementation of class clusters. You can ignore it if writing a class that provides only instances of itself.