Objective C 运行 'private' 一个 .mm 文件中定义的方法来自另一个 .mm 文件

Objective C run 'private' method defined in one .mm file from another .mm file

关于在 Obj-C 中访问 'private'(我从技术上讲,Obj-C 中没有私有方法这样的东西)消息有很多问题。并且有很多问题解决 No visible @interface for SomeClass declares the selector 'SomeMethod'。但是,没有一个同时解决这两个问题。

所以这是一些代码。 Example.h

#import <Cocoa/Cocoa.h>

@interface Example : NSView

@end

Example.mm

#import "Example.h"
@interface Example()
- (void) printWordOne:(NSString*) firstWorld wordTwo:(NSString*) secondWord;
@end


@implementation Example

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.
}

- (void) printWordOne:(NSString*) firstWorld wordTwo:(NSString*) secondWord{
    NSLog(@"The two words are %@ %@", firstWorld, secondWord);
}

@end

ViewController.h

#import <Cocoa/Cocoa.h>
#import "Example.h"
@interface ViewController : NSViewController{
    IBOutlet Example *example;

}

@end

故事板中已连接 IBOutlet。

ViewController.mm

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // Do any additional setup after loading the view.
    [example printWordOne:@"Hello" wordTwo: @"World"];
}

- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];

    // Update the view, if already loaded.
}

@end

我遇到的问题是此方法调用。 [example printWordOne:@"Hello" wordTwo: @"World"];

错误是No visible @interface for 'Example' declares the selector 'printWordOne:wordTwo'

我需要一种无需在 Example.h 文件中声明即可调用该函数的方法。如果我 #import Example.mm 在我的 ViewController.mm 文件中,我得到以下内容:

duplicate symbol _OBJC_CLASS_$_Example in:
    /path/Example.o
    /path/ViewController.o
duplicate symbol _OBJC_METACLASS_$_Example in:
    /path/Example.o
    /path/ViewController.o
ld: 2 duplicate symbols for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

我知道使用 class_copyMethodList 我可以获取方法列表并从 ViewController.mm 中列出该方法。但是无论如何还是要执行该方法。

如有任何帮助,我们将不胜感激。

您可以简单地将类别声明为 Example class,并在 ViewController.mm:

中使用私有方法声明
#import "ViewController.h"

@interface Example()
- (void) printWordOne:(NSString*) firstWorld wordTwo:(NSString*) secondWord;
@end

@implementation ViewController
// ...
@end