我有一个要求,需要创建一个只在应用程序处于活动模式时运行的后台处理器。我已经尝试着制作了一个我想要实现的骨架,但是却无法使它工作。
我希望这个后台处理器在应用程序进入非活动状态时进入睡眠状态,并在应用程序恢复到活动模式时继续运行。我在下面提供了我的代码骨架。请问有人能帮我解决问题吗?
AppDelegate.h
#import <Foundation/Foundation.h>
@class BackgroundProcessor;
@interface AppDelegate_iPhone : UIResponder<UIApplicationDelegate>{
BackgroundProcessor* processor;
}
@property(nonatomic) BackgroundProcessor *processor;
@end
AppDelegate.m
#import "AppDelegate_iPhone.h"
#import "BackgroundProcessor.h"
@implementation AppDelegate_iPhone
@synthesize processor;
-(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
processor = [[BackgroundProcessor alloc]init];
[processor Start];
return YES;
}
-(void) applicationDidEnterBackground:(UIApplication *)application
{
[processor Sleep];
NSLog(@"Entered Background");
}
-(void) applicationDidBecomeActive:(UIApplication *)application
{
[processor Resume];
NSLog(@"Became Active");
}
@end
BackgroundProcessor.h
#import <Foundation/Foundation.h>
@interface BackgroundProcessor : NSObject
{
NSThread* processor;
}
@property (nonatomic) NSThread *processor;
-(void) Start;
-(void) Sleep;
-(void) workloop;
-(void) Resume;
@end
BackgroundProcessor.m
#import "BackgroundProcessor.h"
@implementation BackgroundProcessor
@synthesize processor;
-(id) init
{
self = [super init];
if(self)
{
processor = [[NSThread alloc] initWithTarget:self selector:@selector(workloop) object:nil];
}
return self;
}
-(void) Start
{
if(processor)
[processor start];
}
-(void) Sleep
{
// [processor
[NSThread sleepForTimeInterval: 0.1];
}
-(void) workloop
{
NSLog(@"Background Processor Processing ....");
[NSThread sleepForTimeInterval:0.1];
}
- (void) Resume
{
NSLog(@"Background Resuming ....");
[NSThread sleepForTimeInterval: 0.1];
}
我无法使工作循环连续运行。希望有人能帮助我解决为什么后台无法运行的问题。
在Joshua Smith的建议下尝试了这个方法
#import "BackgroundProcessor.h"
@implementation BackgroundProcessor
-(id) init
{
self = [super init];
if(self)
{
queue = [[NSOperationQueue alloc] init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(workloop) object:nil];
[queue addOperation:operation];
}
return self;
}
-(void) workloop
{
NSLog(@"Sleeping for 10 seconds");
sleep(10);
NSLog(@"Background Processor Processing ....");
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(workloop) object:nil];
[queue addOperation:operation];
}
@end