Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issue with mixing Objective C and C++ in single file

I am having .mm file, in which i have some c++ function and few line of objective c.

For ex.

void display()
{
....
....
}

void doSomthing()
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
[button addTarget:??? action:@selector(display) ....]

[rooView addSubView:UIButton];
}

I am not getting the way how i could call display function which defined in same mm file? what will be my addTarget? (self/this not working in my case )

like image 588
chetan rane Avatar asked Jan 23 '26 01:01

chetan rane


2 Answers

You cannot use @selector() to reference a function, you can only use it to reference an objective-c method.

Further the UIButton class is not capable of performing a function call when it is clicked. It can only perform an objective-c method.

You can however, "wrap" an objective-c method around the function:

- (void)display:(id)sender
{
    display();
}

Allowing this:

[button addTarget:self action:@selector(display:) ....];

But if you are writing your own display() function, then you may as well just put it's contents in the display method.

like image 73
Abhi Beckert Avatar answered Jan 24 '26 15:01

Abhi Beckert


You need an Objective-C class and some methods to wrap your C++ function calls.

@interface WrapperClass : NSObject

-(void) display;

@end

void display()
{
....
....
}

@implementation WrapperClass

-(void) display
{
    display();
}

@end

static WrapperClass* wrapperObj = nil;

void doSomthing()
{
    if (wrapperObj == nil)
    {
        wrapperObj = [[WrapperClass alloc] init];
    }

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    [button addTarget: wrapperObj action:@selector(display) forControlEvents: whatever];
    [rooView addSubView:UIButton];
}
like image 33
JeremyP Avatar answered Jan 24 '26 13:01

JeremyP