#import <Foundation/Foundation.h> #import "Soldier.h" #import "Commander.h" int main(int argc, const char * argv[]) { @autoreleasepool { Commander *shizhang=[[Commander alloc]init]; //block // [shizhang command]; //delegate // [shizhang commandForDelegate]; //selector [shizhang command]; } return 0; }
#import <Foundation/Foundation.h> @protocol killJapaneseDelegate <NSObject> -(void)getMessage:(int)num; @end @interface Soldier : NSObject //block -(void)killGhostByCommand:(NSString *)com andBlock:(void (^)(int))block; -(int)killGhost; @property (strong)id<killJapaneseDelegate>delegate; //delegate -(void)sendMessage; //selector -(void)useSelector:(SEL)sel andObj:(id)obj; @end
#import "Soldier.h" @implementation Soldier -(int)killGhost{ int a=0; for (int i=1; i<=10; i++) { a+=10; NSLog(@"%d刀:张嘎杀了%d个鬼子",i,a); sleep(1); } NSLog(@"哎呀,腰子闪了"); return a; } -(void)killGhostByCommand:(NSString *)com andBlock:(void (^)(int))block{ if ([com isEqualToString:@"杀鬼子"]) { NSLog(@"收到命令,师长我一刀能杀10个!"); block([self killGhost]); }else{ NSLog(@"你说啥,我听不懂"); } } -(void)sendMessage{ NSLog(@"收到命令,师长我一刀能杀10个!"); [self.delegate getMessage:[self killGhost]]; } //selector -(void)useSelector:(SEL)sel andObj:(id)obj{ [obj performSelector:sel]; } @end
#import <Foundation/Foundation.h> #import "Soldier.h" @interface Commander : NSObject<killJapaneseDelegate> //block -(void)command; //delegate -(void)commandForDelegate; //selector -(void)howToKillGhost; -(void)sendSelector; @end
#import "Commander.h" @implementation Commander //block -(void)command{ Soldier *zhangga=[[Soldier alloc]init]; void (^block)(int)=^(int num){ NSLog(@"师长:才杀了%d个,还有脸回来",num); }; [zhangga killGhostByCommand:@"杀鬼子" andBlock:block]; } //delegate -(void)commandForDelegate{ Soldier *zhangga=[[Soldier alloc]init]; zhangga.delegate=self; [zhangga sendMessage]; } -(void)getMessage:(int)num{ NSLog(@"师长:才杀了%d个,还有脸回来",num); } //selector -(void)howToKillGhost{ NSLog(@"如今传你绝学,一刀杀十个"); Soldier *s=[[Soldier alloc]init]; NSLog(@"师长:才杀了%d个,还有脸回来",[s killGhost]); } -(void)sendSelector{ Soldier *zhangga=[[Soldier alloc]init]; [zhangga useSelector:@selector(howToKillGhost:) andObj:self]; } @end