views:

42

answers:

4

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.

A: 

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.

mipadi
A: 

Yes, they are call class messages. Use + instead of - when defining a message.

Like this:

@interface MyClass : NSObject 
{

}

+ (void) callingMyMethod;
Pablo Santa Cruz
+2  A: 

Yes. Just use a + instead of a - when declaring the method:

+ (void)callingMyMethod
{
   ...
}
Carl Norum
A: 

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
}
Conceited Code