2

Is there a way to access a method from an other class without creating an object in Objective-C?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
emy
  • 664
  • 1
  • 9
  • 22
  • 1
    Yes, class methods? You add `+` instead of `-` infront of method declarations and then you can invoke it like `[MyClass myMethod];` – LuckyLuke Nov 16 '12 at 15:27
  • How is it? could u tell about it ? – emy Nov 16 '12 at 15:29
  • Google class methods in objective c. They are methods that belong to the class instance rather then an object of a particular class. – LuckyLuke Nov 16 '12 at 15:30
  • 1
    you should give NSNotificationCenter a try: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html – CarlJ Nov 16 '12 at 15:37

3 Answers3

8
@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"];
danh
  • 62,181
  • 10
  • 95
  • 136
5

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)];.

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
2

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.

Asif Mujteba
  • 4,596
  • 2
  • 22
  • 38
  • 1
    There's no such thing as a static method in Objective-C. Methods prefixed with a `+` are class methods, which is something entirely different. – jlehr Nov 16 '12 at 17:15