I see that the UIColor class can call the variable like this [UIColor redColor]; How can I write my class to do the same thing? Also, can I have a method only for class, for example, like this:
[MyClass callingMyMethod];
Thank you.
I see that the UIColor class can call the variable like this [UIColor redColor]; How can I write my class to do the same thing? Also, can I have a method only for class, for example, like this:
[MyClass callingMyMethod];
Thank you.
You have to create a class method. Class methods are defined like instance method, but have a + instead of a -:
@interface MyClass : NSObject
+ (id)classMethod;
- (id)instanceMethod;
@end
@implementation MyClass
+ (id)classMethod
{
return self; // The class object
}
- (id)instanceMethod
{
return self; // An instance of the class
}
Note that within a class method, the self variable will refer to the class, not an instance of the class.
Yes, they are call class messages. Use + instead of - when defining a message.
Like this:
@interface MyClass : NSObject
{
}
+ (void) callingMyMethod;
Yes. Just use a + instead of a - when declaring the method:
+ (void)callingMyMethod
{
...
}
Use a + instead of the -. This is called a class method and is used to for initializing and return the object.
@interface SomeClass : NSObject
+ (id)callingMyMethod;
- (id)otherMethod;
@end
@implementation SomeClass
+ (id)callingMyMethod
{
return self; // The class object
}
- (id)otherMethod
{
return self; // An instance of the class
}