是否可以在类外声明Objective-C方法?

Sta*_*aro 10 c methods objective-c

我知道你可以在类之外声明一个C函数,但是可以在类之外声明一个Objective-C方法吗?

例:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

jus*_*tin 5

您可以为此使用类别

作为实例方法:

@interface NSObject (MONStuff)
- (void)printHelloOC;
@end

@implementation NSObject (MONStuff)
- (void)printHelloOC
{
  NSLog(@"Hello.");
}
@end

// in use:

NSObject * obj = ...;
[obj printHelloOC];
Run Code Online (Sandbox Code Playgroud)

作为类方法:

@interface NSObject (MONStuff)
+ (void)printHelloOC;
@end

@implementation NSObject (MONStuff)
+ (void)printHelloOC
{
  NSLog(@"Hello.");
}
@end

// in use:

[NSObject printHelloOC];
Run Code Online (Sandbox Code Playgroud)

当然,您必须将其与一个类相关联-因此它与您发布的不完全相同,但是它是一个正式定义类声明之外的一个封闭定义+声明。


Ric*_*III 5

这取决于。您可以在运行时添加方法来执行类似的操作:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但这是在@class构造之外进行的,它实际上只是掩盖了类别发生的情况。