我正在搞乱使用对象来启动后台线程,但是当我调用对象方法来调用将产生后台线程的方法时,什么也没有发生。我有点不明白为什么,看起来 -init 函数甚至没有被调用。无论如何,这就是我所拥有的:
视图控制器.h
#import <UIKit/UIKit.h>
#import "Threader.h"
@interface ViewController : UIViewController
@property(nonatomic, strong) Thread* threadedObject;
- (IBAction)StartBackgroundThreadButtonClicked:(id)sender;
@end
视图控制器.m
#import "ViewController.h"
#import "Threader.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_threadedObject = [[Threader alloc]init];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)StartBackgroundThreadButtonClicked:(id)sender {
NSLog(@"Clicked.");
[_threadedObject RunInBackground];
}
@end
线程器.h
#import <Foundation/Foundation.h>
@interface Threader : NSObject
@property(nonatomic) bool IsFinishedRunning;
@property(nonatomic) bool IsThreading;
//Constructor and Destructor
-(id)init;
-(void)dealloc;
-(void)RunInBackground;
-(void)WaitForTenSeconds;
@end
Threader.m
#import "Threader.h"
@implementation Threader
//constructor
-(id)init{
[super init];
if(self != nil)
{
_IsFinishedRunning = NO;
_IsThreading = NO;
}
return self;
}
//destructor
-(void)dealloc{
[super dealloc];
}
//Runs a thread in the background
-(void)RunInBackground{
NSLog(@"Initiating thread...");
[self performSelectorInBackground:@selector(WaitForTenSeconds) withObject:nil];
}
//Waits for 10 seconds, then sets IsFinishedRunning to YES
-(void)WaitForTenSeconds{
NSLog(@"Starting to run in the background.");
_IsThreading = YES;
sleep(10);
_IsFinishedRunning = YES;
NSLog(@"Finished running in the background.");
}
@end
当我运行程序时,这是我的输出(我点击了几次按钮)
2013-05-17 15:30:57.267 ThreadedObjects Clicked。
2013-05-17 15:30:59.003 单击了 ThreadedObjects。
2013-05-17 15:30:59.259 点击了 ThreadedObjects。
2013-05-17 15:30:59.443 单击了 ThreadedObjects。
2013-05-17 15:30:59.675 单击了 ThreadedObjects。
我应该收到消息,告诉我 Threader 对象已创建,并且它正准备启动后台线程,该线程已生成,然后在 10 秒后,该线程已完成运行。那么,我明显的错误在哪里?