IOS--Operation Object基础
AppDelegate.m
1 #import "AppDelegate.h" 2 #import "TestController.h" 3 4 @interface AppDelegate () 5 @property(nonatomic,strong)TestController *controller; 6 @end 7 8 @implementation AppDelegate 9 10 11 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 12 // Override point for customization after application launch. 13 self.window = [[UIWindow alloc]init]; 14 15 self.controller = [[TestController alloc]init]; 16 17 self.window.rootViewController = self.controller; 18 19 [self.window makeKeyAndVisible]; 20 return YES; 21 }
MyOperation.h
1 #import <Foundation/Foundation.h> 2 3 @interface MyOperation : NSOperation 4 5 @end
MyOperation.m
1 #import "MyOperation.h" 2 3 @implementation MyOperation 4 5 -(void)main 6 { 7 for (int i=1; i<10; i++) { 8 [NSThread sleepForTimeInterval:1]; 9 NSLog(@"thread%d",i); 10 } 11 } 12 13 @end
TestController.m
1 #import "TestController.h" 2 #import "TestView.h" 3 #import "MyOperation.h" 4 5 @interface TestController() 6 7 @property(nonatomic,strong)UIButton *button; 8 @property(nonatomic,strong)MyOperation *myOperation; 9 10 @end 11 12 @implementation TestController 13 14 - (void)viewDidLoad 15 { 16 [super viewDidLoad]; 17 18 _myOperation = [[MyOperation alloc]init]; 19 20 _button = [UIButton buttonWithType:UIButtonTypeSystem]; 21 22 _button.frame = CGRectMake(0, 20, 100, 20); 23 [_button setTitle:@"Hello" forState:UIControlStateNormal]; 24 25 [_button addTarget:self action:@selector(start:) forControlEvents:UIControlEventTouchUpInside]; 26 27 28 [self.view addSubview:_button]; 29 30 } 31 32 -(void)start:(UIButton*)sender 33 { 34 NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 35 [queue addOperation:_myOperation]; 36 37 /* 38 使用 NSInvocationOperation 39 NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(thLoop) object:nil]; 40 NSOperationQueue *queue2 = [[NSOperationQueue alloc]init]; 41 [queue2 addOperation:operation]; 42 */ 43 44 /* 45 使用 NSBlockOperation 46 NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{ 47 for (int i=1; i<10; i++) { 48 [NSThread sleepForTimeInterval:1]; 49 NSLog(@"blockThread%d",i); 50 } 51 52 }]; 53 54 NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{ 55 for (int i=1; i<10; i++) { 56 [NSThread sleepForTimeInterval:1]; 57 NSLog(@"block2Thread%d",i); 58 } 59 60 }]; 61 62 63 NSOperationQueue *queue3 = [[NSOperationQueue alloc]init]; 64 [queue3 addOperation:operation2]; 65 66 //operation3依赖operation2,当operation2执行完毕再执行operation3 67 [operation3 addDependency:operation2]; 68 69 [queue3 addOperation:operation3]; 70 */ 71 72 } 73 74 /* 75 回调函数 76 -(void)thLoop 77 { 78 for (int i=1; i<10; i++) { 79 [NSThread sleepForTimeInterval:1]; 80 NSLog(@"newThread%d",i); 81 } 82 } 83 */ 84 85 @end