协议

objective-c中的协议相当于C++中的接口。新建工程:agreeMent,修改代码如下:

//
//  main.m
//  agreeMent
//
//  Created by cloud on 13-3-9.
//  Copyright (c) 2013年 cloud. All rights reserved.
//

#import <Foundation/Foundation.h>
@protocol myAgreeMent

- (void) print;
@required
- (void) sayHello;
@optional
-(void) getNumber;
@end


@interface Car:NSObject <myAgreeMent>
{
    int code;
}
@end

@implementation Car
-(id) init
{
    if (self=[super init]) {
        code=10;
    }
    return (self);
}

-(void) print
{
    NSLog(@"The number is %d",code);
}

-(void) sayHello
{
    NSLog(@"car say hello");
}
@end

@interface Tire:NSObject <myAgreeMent>
{
    int code;
}
@end

@implementation Tire
-(id) init
{
    if (self=[super init]) {
        code=12;
    }
    return (self);
}
-(void) print
{
    NSLog(@"The number is %d",code);
}

-(void) sayHello
{
    NSLog(@"tire say hello");
}
@end



int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        Car* car;
        car=[[Car alloc] init];
        Tire* tire;
        tire=[[Tire alloc] init];
        [car print];
        [car sayHello];
        [tire print];
        [tire sayHello];
        
        
        
    }
    return 0;
}

运行结果如下:


说明,一个类可以有多个协议。@interface Car:NSObject <myAgreeMent1,myAgreeMent2>

协议中@optional表示这个方法可以实现也可以不实现,否则必须在类中实现方法




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值