Objective-C: Class vs Instance Methods? - objective-c

In Objective-C, while creating any class, how do we decide whether we need to mark a method as Class method or Instance Method ?
I know the difference between the 2, but my question is how to decide the marking (+/-) for any method ?

+ denotes a class method, - denotes an instance method. You create class or instance methods where your application needs them. Should you actually know the difference between the two, and your application, then you should have no problems understanding when to use which.
I believe you don't know the differences in how they apply to your application, so here's a small primer:
You use a class method when you need to access some behaviour globally through all instances of that class. i.e., [[self class] someSpecialThing];
You also use a class method when you need a factory method; and
Everywhere else, you use an instance method.

Related

Where to Use Class Method ,Instance Method in Objective-C

"Instance" mean in Objective-C?
Kindly tell me where to use Class Method And where to use Instance Method,also tell me where we use (Instacetype) method?
why/where we use multi Parameters?
A class method is a method whose self parameter is a reference to the class's class object.
An instance method is a method whose self parameter is a reference to a specific instance of the class.
Those are the technical differences.
A more practical answer is that an instance method operates on a single instance of the class, while a class method operates at a more global, non-specific level. A class method can act as a factory method, such as NSString's stringWithFormat: method. It can also be used to configure behavior that will affect all instances of the class. It can also be used to operate on a collection of instances of the class, such as sorting or filtering.
instancetype is a keyword that can be used as a placeholder for the current class's type. It says to the compiler: pretend that I wrote <my class name> here, so if you see the result of this method assigned somewhere, you know what type it's supposed to be.

Objective-C: Use singleton vs. use class as an object?

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.

What's the difference of instance method and class method in Objective-C? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Objective-C: Class vs Instance Methods?
Objective-C - difference between class method and static method?
In ObjC, A single dash before a method name means it's a instance method. A plus before a method name means it's a class method. but what is the difference in programming?
The difference between a class method and an instance method is that an
instance method requires an instance of the class on which it will
(generally) operate. The message to invoke an instance method must be
sent to an instance of a class.
Probably the most common single use of class methods is object
factories; messages that you send to a class to create an instance
configured according to the parameters you've sent in. For example in
Cocoa the NSString class has several class methods named
stringWithSomethingOrOther: that will create a new NSString object and
hand it back to you.
On the other hand, NSString also has many instance methods -
operations which really have no meaning without an actual instance to
work with. A commonly-used one might be the length method, which tells
you how many characters are in the specific NSString instance to which
the message is sent.
Also see this.
What is the difference between class and instance methods?
An instance method is invoked on objects. A class method is invoked on class.
For example the line:
SomeClass *object = [[SomeClass alloc] init];
Here you can see that the "alloc" works on "SomeClass" and not on "object".
Whereas:
[object callMyFunction]; will act on "object" and not "class". This is an instance method.
The main difference with those two is the former one ie with single dash before it is only called by the instance of that class where it is declared ie one have to create one instance of that class means one object for that class and using . one can call the instance method
In class method, the later one can be called directly using the class name. To call class methods one dosen't need any object.
Please refer this link from apple developers documents

Objective C: Giving all objects of a class a pointer to a singleton of another class

I have a custom ViewController class and many instances of it, and I want them all to be able to message the same Model (another custom class, only one instance). Passing pointers to the Model along to new instances of the ViewController seems impractical, especially since the model is lazily instantiated. What is the cleanest, most idiomatic, ARC way to do this?
Usually a singleton in ObjC will have a class method that serves as an accessor for the single instance. The convention is for this to be called either defaultX or sharedX. If your model class is indeed a singleton, you should already have such a method. Since class names are globally available, all you have to do to access the instance anywhere in your program is [MyModelClass sharedModel].

Class methods and instance methods - when/when not to use them?

I was wondering when and when not to use class methods and instance methods. I need some practical examples. I am really confused. Another question: can't we do exactly the same things with instance methods that we can with class methods?
Class methods: The method isn't tied to any specific object. In a way it acts like a free function in the class's namespace. No 'self' pointer. For instance [UIScreen mainScreen] is a class method because there's only one screen and there's no need to care about multiple 'screen instances'.
Instance method: Tied to a specific object.
This applies to most OO languages, not just obj-C.
At the implementation level, an instance method call contains a hidden pointer to a data structure (the object), a class method does not.
The practical question to ask is whether your call requires sending the call some specific data which is or could best be encapsulated as instance data inside an object, or not.
You (usually) can do the same thing with class methods as instance methods, but then you have to explicitly pass the object as a visible parameter in the call, which is uglier looking and also potentially disables some method override features of the Objective C language.
Use class methods for utility functions and Instance methods for object oriented stuff.
Eg. For Mathematical calculation (eg sin x ) use class method. But for invoking a behavior specific to an object.. use instance method ..
A class method as the name implies is bounded to the class. You can invoke them just with the name of the particular class. These can be normally exposed methods of a class.
For example
NSArray
+ (id)arrayWithArray:(NSArray *)array;.
You call it with the class name NSArray. What you expect is just a creation of a object of the type of that particular class. This doesn't need an object to invoke. Also these are very basic method required so its better to make it as a class method.
On the other hand instance method as the name implies is very much bound to the instance. Object is an entity that encapsulates state (ivars) and behaviors (methods) of a class. This can be very specific to the object.
For example
- (NSUInteger)count;
Lets take NSArray *a and NSArray *b. If a contains 5 items whereas b contains 4, instance methods called upon these instances will produce different results. And thats why we need instances to be initialized while invoking instance method. They work on the context(or state) of the object they are been called upon. Also they are not exposed as the class methods are.
Hope this helps.
If you want to use instance objet or instance variable you have to go with instance Methods.
Bcz Inside the class you cant access the Instance instance objet or instance variable.
Class methods are static methods.