Skip to content

Instantly share code, notes, and snippets.

@huytd
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huytd/5a114c1337193fd88032 to your computer and use it in GitHub Desktop.
Save huytd/5a114c1337193fd88032 to your computer and use it in GitHub Desktop.
Objective-C class, inheritance, protocol, delegate demo
#import <Foundation/Foundation.h>
@interface DaGiac: NSObject {
int a;
int b;
}
@property int a;
@property int b;
-(float) getDienTich;
@end
@implementation DaGiac
@synthesize a, b;
-(float)getDienTich {
return 0;
}
@end
/////////////////////////////////////////////////////
@protocol DaGiacDelegate
-(void)daGiacDelegateWannaSayHello;
@end
/////////////////////////////////////////////////////
@interface HinhChuNhat: DaGiac {
id <DaGiacDelegate> delegate;
}
@property (nonatomic, retain) id delegate;
@end
@implementation HinhChuNhat
@synthesize delegate;
-(float)getDienTich {
[self.delegate daGiacDelegateWannaSayHello];
return self.a * self.b;
}
@end
@interface TamGiac: DaGiac
@end
@implementation TamGiac
-(float)getDienTich {
return 1;
}
@end
/////////////////////////////////////////////////////
@interface Application: NSObject <DaGiacDelegate>
@end
@implementation Application
-(id) init {
HinhChuNhat *hcn = [[HinhChuNhat alloc] init];
hcn.delegate = self;
TamGiac *tg = [[TamGiac alloc] init];
hcn.a = 10; hcn.b = 2;
NSLog(@"HCN = %f ----- TG = %f",[hcn getDienTich], [tg getDienTich]);
}
-(void) daGiacDelegateWannaSayHello {
NSLog(@"HELLO!");
}
@end
/////////////////////////////////////////////////////
int main()
{
Application* app = [[Application alloc] init];
return 0;
}
@huytd
Copy link
Author

huytd commented Jun 24, 2014

The output should be:

2014-06-24 06:51:04.765 program[229] HELLO!
2014-06-24 06:51:04.768 program[229] HCN = 20.000000 ----- TG = 1.000000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment