Class methods are static methods? Is this argument true? So if we declare NSString since alloc is a class methods
NSString *hello = [[NSString alloc] init]; class method
[hello isEqualtoString: @"Hello"]; instance method
Class methods are static methods? Is this argument true? So if we declare NSString since alloc is a class methods
NSString *hello = [[NSString alloc] init]; class method
[hello isEqualtoString: @"Hello"]; instance method
In Object Oriented Programming a class method is a method/function that is applied to/called by a class and not a particular instance of it, ie an object of that class. An instance method is a method called directly on an object.
In some languages each class is represented by a Class object and so a class method is an instance method of that object. This is useful to apply reflection and introspection.
In objective-c class methods are defined by using the symbol +
preceding its declaration, whereas instance ones use the -
before them. Here is an example:
@interface Rectangle : NSObject
+ (void)join:(Rectangle *)firstRect withAnother:(Rectangle *)secondRect;
- (void)area;
@end
Class methods are frequently used when you do not need to refer to a particular object, or you have to change all of them or you just need a place for a function that is not related to instance objects.
You said static
in your question. You are probably referring to languages like Java which have the keyword static come before the declaration of a class method. In objective-c the keyword static has the same meaning of it used in C.
As a reference you can have a look at this answer on SO or at this paragraph.
You can think of a class method as being similar to a static
method in C++, as in
[NSString alloc] <=> /* hypothetical */ NSString::alloc()
But behind the scenes, there are major differences. For example, in a C++ static
method you cannot use this
; in an Objective-C class method, self
is perfectly valid and refers to the class object.