Iphone Cocoa Touch中的协议与直接消息
在我的应用程序中,有些地方我必须调用其他类中的一组代码。我通常使用协议来实现这一点Iphone Cocoa Touch中的协议与直接消息,iphone,objective-c,cocoa,protocols,public-method,Iphone,Objective C,Cocoa,Protocols,Public Method,在我的应用程序中,有些地方我必须调用其他类中的一组代码。我通常使用协议来实现这一点 // Teacher.m @protocol TeacherProtocol - (void)assignHomeWork; - (void)respondToAssingment; @end for (Student *student in self.studentInClass) { [student assignHomeWork]; } // Student.m <TeacherProto
// Teacher.m
@protocol TeacherProtocol
- (void)assignHomeWork;
- (void)respondToAssingment;
@end
for (Student *student in self.studentInClass) {
[student assignHomeWork];
}
// Student.m <TeacherProtocol>
- (void)assignHomeWork {
[self receivedAssignmentPaper];
}
// Nerd.m : Student
- (void)assignHomeWork {
[super assignHomeWork];
[self listenWithAttention];
}
// Douchebag.m : Student
- (void)assignHomeWork {
[super assignHomeWork];
[self listenToHisIPod];
}
// Blonde.m : Student
- (void)assignHomeWork {
[super assignHomeWork];
[self makeUp];
}
问题是,我应该将切换转换为房间对象的协议,还是将其作为这样的公共方法?还有其他影响吗 在这两种情况下,我都不会使用协议 在第一种情况下,所有子类都是student类的直接分层子类,因此如果在student头中定义函数,则可以在其所有子类中实现或覆盖该函数 只有当你计划将函数添加到一个不是学生类的子类的对象时,我才会把它变成一个协议
请参阅协议文档,在页面顶部有一个简短的列表,其中协议是有意义的:是的,你说得对,我举了一个错误的例子。在我的实际代码中,我将协议与完全不同的类相一致。
// Room.m
- (IBAction)mainSwitchWasToggle:(id)sender {
[self.mainLightBulb toggle];
}
// MainLightBulb.m
- (void)toggle {
if ([self.bulb isTurnOn]) {
[self.bulb turnOff];
} else {
[self.bulb turnOn];
}
}