How to call a method on .mm file from a objective c class

别说谁变了你拦得住时间么 提交于 2020-01-05 07:04:41

问题


I am working on an iphone app. I need to call a method on a .mm file. Here is simplified version of the problem:

ViewHelper.h

- (void)testMtd;

ViewHelper.mm (notice this is .mm)

- (void)testMtd{
   NSLog(@"Call reached mm");
}

SomeViewController.m (import to ViewHelper.h omitted for clarity)

- (void)someCallerMtd{
   NSLog(@"before");
   [viewHelper testMtd]; //call does not work
   NSLog(@"after");
}

I see "before" and "after" in the log, but "Call reached mm" never gets printed. Are there special rules to call obj c methods in a .mm file? What am I missing here?


回答1:


First, it has nothing to do with .mm file, it is still objective-c clss. Second, Your mistake is not allocating ViewHelper.

The solutions is either alloc your ViewHelper or make (void)testMtd publicly. depend on what your need.

either change your SomeViewController.m:

- (void)someCallerMtd{
   NSLog(@"before");
   viewHelper = [[ViewHelper alloc] init];
   [viewHelper testMtd]; 
   [viewHelper release];
   NSLog(@"after");
}

or change your ViewHelper :

//ViewHelper.h
+ (void)testMtd;

//ViewHelper.mm
+ (void)testMtd{
   NSLog(@"Call reached mm");
}

- (void)someCallerMtd{
       NSLog(@"before");
       [ViewHelper testMtd]; //remember to use ViewHelper class. not viewhelper.
       NSLog(@"after");
    }



回答2:


The most likely reasons that your -testMtd method never gets called is that viewHelper is nil. Make sure that it points to a valid instance of the ViewHelper class. It's legal in Objective-C to send a message to a nil pointer, but no method will be called in that case.



来源:https://stackoverflow.com/questions/9452343/how-to-call-a-method-on-mm-file-from-a-objective-c-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!