OC学习:协议、类目和延展

本文详细介绍了如何在Objective-C中定义一个遵循特定协议的Student类,并实现了协议中指定的方法,同时展示了类目和延展如何扩展类的功能。

定义一个Student类

#import <Foundation/Foundation.h>
//协议StudentProtocol
@protocol StudentProtocol <NSObject>
@property (nonatomic,assign) NSInteger age;
-(void) fun1;
@end
//Student类遵循协议StudentProtocol
@interface Student : NSObject <StudentProtocol>

@end
//类目
@interface Student (myCatagory)
@property (nonatomic,strong) NSString *name;
-(void) fun2;
@end
//延展
@interface Student ()
@property (nonatomic,strong) NSString *sex;
-(void) fun3;
@end
#import "Student.h"
//倒入头文件objc/runtime.h实现objc_……方法
#import <objc/runtime.h>
@implementation Student
//协议StudentProtocol的方法实现
@synthesize age = _age;
-(void) fun1 {
    NSLog( @"fun1");
}
//延展的实现
@synthesize sex = _sex;
-(void) fun3 {
    NSLog(@"fun3");
}
@end

//类目的实现
@implementation Student (myCatagory)
//在类目中下面语法有误,不通过
//@synthesize name = _name;
//写setter方法
-(void) setName:(NSString *)name {
    objc_setAssociatedObject(self, @selector(setName:), name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
//写getter方法
-(NSString *) name {
    return objc_getAssociatedObject(self, @selector(setName:));
}
-(void) fun2 {
    NSLog(@"fun2");
}

@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值