Is there a way to access a method from an other class without creating an object in Objective-C?
3 Answers
@interface APotentiallyBadIdea : NSObject
+ (void)potentiallySillyUnmooredMethod:(NSString *)string;
@end
@implementation APotentiallyBadIdea
+ (void)potentiallySillyUnmooredMethod:(NSString *)string {
NSLog(@"ask yourself why this isn't on a real object %@", string);
}
@end
Call it like this:
[APotentiallyBadIdea potentiallySillyUnmooredMethod:@"this might be ok if it's part of a more complete object implementation"];
Comments
I suspect you are really looking for class methods; Objective-C's equivalent to other languages' static methods. See: What is the difference between class and instance methods?
To define one:
@implementation MONObject
+ (void)classMethod { ... }
@end
In use: [MONObject classMethod]
If you want the instance method as a callable C function, see class_getInstanceMethod, or simply IMP imp = [MONClass instanceMethodForSelector:@selector(someSelector)];.
Comments
Use + sign to define the method which would make it static method, accessible via class name like this
in .h file
+ (void) someMethod;
in .m file
+ (void) someMethod {}
than you can easily access it via class name in another file
[ClassName someMethod];
Note: don't forget to import that class.
1 Comment
+ are class methods, which is something entirely different.
+instead of-infront of method declarations and then you can invoke it like[MyClass myMethod];