Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare an Objective-C method outside a class?

I know that you can declare a C function outside of a class, but is it possible to declare a Objective-C method outside of a class?

Example:

// Works
void printHelloC()
{
    NSLog(@"Hello.");
}

// Error
-(void) printHelloOC
{
    NSLog(@"Hello.");
}

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        printHelloC();
        [self printHelloOC];// 'self' obviously would not work but you get the idea
    }
    return 0;
}
like image 857
Stas Jaro Avatar asked Feb 02 '12 01:02

Stas Jaro


People also ask

Can methods be declared outside of a class?

The definitions of class methods can be anywhere outside of the class. When you define a class method outside the class, you need to prefix the method name with the class name and scope resolution operator. The important part is not to use the scope access keywords, such as private , protected or public .

Can we define a method outside the class how and why?

No its not possible. In java everything (objects) belongs to some class. So we can not declare function(method) outside a class.

Can you write C in Objective-C?

You really can't use C in Objective-C, since Objective-C is C. The term is usually applied when you write code that uses C structures and calls C functions directly, instead of using Objective-C objects and messages.


1 Answers

It depends. You can do something similar with method adding at runtime:

#import <objc/runtime.h>

void myCustomMethod(id self, SEL _cmd, id arg1, id arg2)
{
    NSLog(@"This is a test, arg1: %@, arg2: %@", arg1, arg2);
}

int main(int argc, char *argv[])
{
    Class NSObjClass = [NSObject class];

    class_addMethod(NSObjClass, @selector(myNewMethod::), (IMP) myCustomMethod, "v@:@@");

    NSObject myObject = [NSObject new];

    [myObject myNewMethod:@"Hi" :@"There"];

    [myObject release];

    return 0;
}

But that is about it outside of a @class construct, and it really just covers up what happens with a category.

like image 177
Richard J. Ross III Avatar answered Nov 04 '22 06:11

Richard J. Ross III