I have a couple question..First of all, what is the best way to implement an inner class that shown in the java code below? (implementing a protocol like an interface in Java)
public class MembershipControl {
public MembershipControl(){
//do something here...
sendMessage sendMsgThread = new SendMessageThread();
Thread sendeMsgThreadInst = new Thread(sendMsgThread);
sendMsgThreadInst.start();
}
public class sendMessageThread implements Runnable {
public void run() {
while (isActive) {
//do something here
}
}
}
Also, as you guys might noticed, the inner class this case will be run on a separate thread. So I have a Java code like this inside of the constructor
sendMessage sendMsgThread = new SendMessageThread();
Thread sendeMsgThreadInst = new Thread(sendMsgThread);
sendMsgThreadInst.start();
I have used something like this in Objective C to spawn a new thread..In the java code, the inner class has a while loop and it runs forever as long as isActive, boolean type variable, is true. Can I just set up an while loop with a boolean type variable like shown in Java code to run the loop forever as long as the boolean variable is true in objective C? Am I supposed to use CFRunLoop?
[NSThread detachNewThreadSelector:@selector(a method here:) toTarget:self wi开发者_如何学编程thObject: an object to be passed];
Trying to port code from one language & API to another line-by-line, construct-by-construct, is a losing battle.
You need to start at a relatively abstract level, read through the various excellent programming guides related to your targeted platform and then solve your problem in whatever fashion best fits that platform.
(Not saying that you are making the aforementioned mistake -- just making sure that others that might read this don't!)
In particular, the Concurrency Programming Guide is likely going to be highly applicable (assuming a working knowledge of Objective-C).
Specifically, what you want to avoid are spawning lots of threads -- no need because you have GCD and NSOperation instead -- and anything that resembles:
while(stillRunning) {
... do something
}
In particular, the latter construct alludes to a polling construct. Polling is bad; it eats CPU, battery, and often makes the app less responsive. The general model on Mac OS X and iOS is to set up some kind of handler -- a dispatch source, run loop event handler, etc... -- and then use CPU only when responding a response-worthy event.
精彩评论