从前有一个公司,公司的名字叫做"来福"。 Xcode->Create a new Xcode project->OS X->Application->Command Line Tool->Product Name is "LaiFu"->Create. 公司里面有一个老板。 New File->Objective-C class->Boss->Subclass of NSObject->Create. 有一天,老板想买一天电脑。 @interface Boss : NSObject - (void)willBuyAComputer; @end @implementation Boss - (void)willBuyAComputer { } @end 刚刚起身忽然想起来,今天要去北京开会。于是老板决定让员工帮他买。老板起草了一份名为“买电脑委托书”的文件。 New File->Objective-C protocol->BuyComputerDelegate->Next->Create. 文件内容为“去帮我买一台电脑”。 @protocol BuyComputerDelegate<NSObject> - (void)buyAComputer; @end 老板把“买电脑委托书”揣在了身上。 in Boss.h #import "BuyComputerDelegate" in @interface @property (assign, nonatomic) id<BuyComputerDelegate> buyComputerDelegate; in Boss.m - (void)willBuyAComputer { [self.buyComputerDelegate buyAComputer]; } 老板发现小明目前闲着没事干。 New File->Objective-C class->XiaoMing->Subclass of NSObject->Create. 老板问小明,“你有时间帮我去买个电脑么?”小明说,“why not?” in XiaoMing.h #import "BuyComputerDelegate" @interface XiaoMing : NSObject <BuyComputerDelegate> in XiaoMing.m @implementation XiaoMing - (void)buyComputer { } @end 老板把“买电脑委托书”交给了小明说,“那你去买吧。” in main.m #import "Boss.h" #import "XiaoMing.h" @autoreleasepool{ Boss *boss = [[Boss alloc] init]; XiaoMing *xiaoMing = [[XiaoMing alloc] init]; boss.buyComputerDelegate = xiaoMing; [boss willBuyComputer]; } 过了一会儿,小明回来了,对老板说,“我买回来了一台电脑。” in XiaoMing.m - (void)buyComputer { NSLOG(@"I has bought a computer."); } 更多 0