iphone - A question of objective-C protocol -
i try learn protocol of objective c.
write 2 files, first 1 firstviewcontroller.h, , in there protocol "print". declare firstviewcontroller class in successviewcontroller delegate method "print". question why console output "c". why can not "b" output? why protocol method did not perform?
#import <uikit/uikit.h> #import "firstviewcontroller.h" @interface successviewcontroller : uiviewcontroller <firstviewcontrollerdelegate> { } @end
#import "successviewcontroller.h" #import "firstviewcontroller.h" @implementation successviewcontroller - (void)viewdidload { firstviewcontroller *firstviewcontroller= [[firstviewcontroller alloc] init]; firstviewcontroller.delegate=self; nslog(@"c"); [super viewdidload]; } -(void) print{ nslog(@"b"); } @end
#import <foundation/foundation.h> @class firstviewcontroller; @protocol firstviewcontrollerdelegate <nsobject> - (void) print; @end @interface firstviewcontroller : nsobject { id <firstviewcontrollerdelegate> delegate; } @property (nonatomic, assign) id <firstviewcontrollerdelegate> delegate; @end
#import "firstviewcontroller.h" @implementation firstviewcontroller @synthesize delegate; @end
because never call print
method. expecting called?
objective-c protocols allow specify class capable of performing actions. in example, successviewcontroller
declared firstviewcontrollerdelegate
, meaning capable of handing duties required firstviewcontroller
of delegate. more of programming contract between classes, 1 can verified compiler.
as side note, classes in objective-c should start capital letter, methods should start lowercase. firstviewcontroller
follows rule, successviewcontroller
not.
Comments
Post a Comment