Question

In my app, there are some places where I have to invoke a set of code in other class. I usually use protocol to do so

// 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];
}

In the above example, its a OK and does make sense. But, in some case that the class should send a message to another and there will never be any other class receive this message.

// Room.m
- (IBAction)mainSwitchWasToggle:(id)sender {
    [self.mainLightBulb toggle];
}

// MainLightBulb.m
- (void)toggle {
    if ([self.bulb isTurnOn]) {
        [self.bulb turnOff];
    } else {
        [self.bulb turnOn];
    }
}

The question is, should I turn toggle into a protocol of Room's object or leave it as a public method like this? Will there be any other impact?

Was it helpful?

Solution

I would not use a protocol in either of those cases.

In the first case all subclasses are direct hierachical children of the student class, so if you define the functions in the student header it can be implemented or overwritten in all of it's subclasses.

I'd only make it an protocol if you ever plan to add the function to an object that is not a children of the student class.

See the documentation of protocols, at the top of the page is a short list where protocols make sense: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top