[performSelector:withObject:afterDelay:] for calling C++ functions?

We can’t use C++ functions as selectors in .mm files as I talked before. We can use another way to implement the delay call:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
   // your C++ code here
});

It would call your C++ code after 5 seconds delay. Still block tricks.

Want to use Global Variable to present instance-related value?

Sometimes we may need to use a global variable to present a value acting like a class member variable, but we couldn’t define it into the class header file (Don’t ask why because cross-platform developers may really have this kind of requirements).

The solution is simple: use a static map as the global variable.

For example, in the mm file:

Top:

static map<YourClassName*, bool> isUsingXFeature;

Initial:

if (shouldUseXFeature())
{
   isUsingXFeature[this] = true;
}

Using:

if (isUsingXFeature[this]) 
{
   doSomething();
}

Of course you can define the global variable as unordered_map to go a fancier way.

 

 

Using C++ method as NSNotificationCenter observer selector

There are many ways to do it. The usual way is to wrap the C++ code inside an Objective-C class.

When sometimes you need to handle NSNotification using C++, it would be simpler. For example, if you want to handle the MPMoviePlayer-finish-playing event, you probably use the following code:

[[NSNotificationCenter defaultCenter] addObserver:???
  selector:@selector(???)
  name:MPMoviePlayerPlaybackDidFinishNotification
  object:???];

What should you fill in to the ???s?

You can’t directly convert a C++ method to a selector because they are totally different like a bird and a balloon. However, you can use a block instead of a selector:

[[NSNotificationCenter defaultCenter] addObserverForName:MPMoviePlayerPlaybackDidFinishNotification 
object:nil 
queue:nil 
usingBlock:^(NSNotification *note) {
     // write any of your C++ code here
 }];

Simple. Right.