Creating a class whose methods can be called without an instance of an object (static class)
I'm new to objective c and i want to create a class containing certain methods that can be called in any of my oth开发者_运维百科er classes, mostly helper methods. im still learning the syntax and i dont know how to declare it properly
kind of like in java Integer.parseInt( );
Thanks!
Static methods in objective-c are called 'class methods' and can be declared with '+' symbol (while instance methods with '-'), e.g.:
- (void) instanceMethod;
+ (void) classMethod;
To call class method use class name:
[MyClass classMethod];
Those are called (unsurprisingly) class methods. You can declare one by using +
instead of -
in the method signature, e.g.
@interface MyInteger : NSObject
+ (MyInteger *)parseInt:(NSString *)str;
@end
This method is then called on the class itself, e.g. [MyInteger parseInt:@"12"]
.
Of course, since this is C, if your class method doesn't actually have much relation to any particular class, you could just define it as a C function instead.
NSInteger myParseInt(NSString *str);
When you see a -
sign in front of a method, it's an instance method. That means you can only call that method on an instance of a class.
If you want to create a class method, all you need to do is change that -
to a +
.
they are called class methods. they are declared and used like this:
@interface MONClass : NSObject
+ (NSString *)convertString:(NSString *)string;
@end
in use:
NSString * converted = [MONClass convertString:string];
精彩评论