2

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

4
  • 1
    Yes, class methods? You add + instead of - infront of method declarations and then you can invoke it like [MyClass myMethod]; Commented Nov 16, 2012 at 15:27
  • How is it? could u tell about it ? Commented Nov 16, 2012 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. Commented Nov 16, 2012 at 15:30
  • 1
    you should give NSNotificationCenter a try: developer.apple.com/library/mac/#documentation/Cocoa/Reference/… Commented Nov 16, 2012 at 15:37

3 Answers 3

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"];
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

1 Comment

There's no such thing as a static method in Objective-C. Methods prefixed with a + are class methods, which is something entirely different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.