Reputation: 4732
I know usually, when you want to call a method on another object, you do:
NewObject *object = [NewObject alloc]init];
[object callMethod];
But I created a class that isn't an object itself meaning it doesn't have properties or memory management. It has a couple methods that calculate some stuff.
From any other class, all I have to do is import the header for this class and do:
#import "MyClass.h"
[MyClass callMethod];
Why in this case do I not have to alloc init? It works just fine.
Upvotes: 1
Views: 4242
Reputation: 3668
because you are calling a class method. You only need to alloc init
objects. Classes only need to be included but not alloc init
ed. So you don't need to init an NSString
class, say.
Edit:
Let's just have some nonsense examples:
+ (void)classMethod {
NSLog("Hi!");
}
[SomeClass classMethod]; // prints Hi!
- (void)instanceMethod { // (say it's an instance method of NSString)
NSLog(self);
}
[@"someNSString" instanceMethod]; // prints someNSString. But you need to have a string first, otherwise you cannot use this method.
Upvotes: 1
Reputation: 906
It sounds like you are trying to call a class method. These are methods which have been defined as:
instead of
The plus sign indicates that the method does not use any fields, and thereby does not need to instantiate the object.
In your example, "object" is an instance of a class "NewObject" which has been allocated memory and initialized. Where-as your example, "MyClass" is only a class which because it has static members declared as above, does not need to be instantiated.
Class methods provide a nice way to combine a bunch of related functions into one place, rather than having them spread out in the regular namespace, as would usually be done in straight C. You can also have both class methods and instance methods in the same class, using the class ones when needed, and instantiating the class to use the instance ones when needed.
EDIT: Changed terminology to refer to class methods instead of static methods.
Upvotes: 1
Reputation: 1615
Class methods are similar to C++ static methods, in that they can be invoked without creating a concrete instance of the class. The usefulness of this is you can call a class's specialized factory methods to create a new instance; or, you can define a utility library under the scope of a class that may or may not provide concrete instances depending on the task.
Look at NSDate and NSNumber are good examples of this in the Foundation framework.
Upvotes: 0
Reputation: 5552
There is a difference between "instance" methods (normal ones), that have to be called on an object and have access to self
, and "class" methods (called static, in many programming languages), that are invoked on the class and thus do not have a self
.
Upvotes: 0