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

被折叠的 条评论
为什么被折叠?



