Object-c初步学习 四

1.category的用法 不修改对象源文件的方式下,给类添加方法

为Student类添加方法

//

// NSObject+StudyCategory.h

//

#import <Foundation/Foundation.h>

#import "Student.h"

#pragma mark 类名后面的(test)代表Category,可以在不修改原来的类文件的情况下,添加新的方法

//pragma mark - 不可以添加新的成员变量

@interface Student (StudyCategory)

  • (void)test:(int)a;

@end

//

// NSObject+StudyCategory.m

//

#import "Student+StudyCategory.h"

#import "Student.h"

@implementation Student (StudyCategory)

  • (void)test:(int)a {

NSLog(@"Sutdent Category test add %i",a);

}

@end

这样就可以为类Student添加test:方法

外部可直接使用

Student *stu = \[\[Student alloc init] autorelease];

stu test:1;

2.protocol的用法 这个是代理,类似java中的interface接口

//
// StudyProtocol.h
//

#import <Foundation/Foundation.h>
@class Button;

#pragma mark <>代表protocol
@protocol StudyProtocol <NSObject>

- (void)onClick:(Button *)btn;

@end

//

// Button.h

//

#import <Foundation/Foundation.h>

@protocol StudyProtocol;

@interface Button : NSObject

@property (nonatomic,retain) id<StudyProtocol> delegate;

  • (void)testClick;

@end

//

// Button.m

//

#import <Foundation/Foundation.h>

#import "Button.h"

#import "StudyProtocol.h"

@implementation Button

  • (void)testClick{

//判断有没有当前方法

if(_delegate respondsToSelector:@selector(onClick:)){

_delegate onClick:self;

}else{

_delegate onClick;

}

}

  • (void)dealloc{

_delegate release;

super dealloc;

}

@end

//

// NSObject+ButtonListener.h

//

#import <Foundation/Foundation.h>

#import "StudyProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface ButtonListener : NSObject <StudyProtocol>

@end

NS_ASSUME_NONNULL_END

//

// ButtonListener.m

//

#import <Foundation/Foundation.h>

#import "ButtonListener.h"

@class Button;

@implementation ButtonListener

  • (void)onClick:(Button *)btn{

NSLog(@"button is click %@",btn);

}

@end

使用方法类似java的接口回调机制

//protocol的用法

Button *btn = \[Button alloc init];

ButtonListener *listener = \[ButtonListener allocinit];

//设置监听器

btn setDelegate: listener;

//模拟点击

btn testClick;

相关推荐
丶玉面小蛟龙39 分钟前
DGCNN网络学习
学习·点云·dgcnn
晓梦林7 小时前
BUUCTF findKey-学习笔记
笔记·学习
0566467 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
炎武丶航9 小时前
汽车功能测试学习(1):FCW前方碰撞预警
功能测试·学习·汽车
qq_1851986915 小时前
SpingBoot3入门学习一
学习
噗噗夹的TA之旅15 小时前
Shader 学习 21:自定义 Render Feature
学习·游戏·unity·c#·游戏引擎·图形渲染
码农小韩16 小时前
AIAgent应用开发——大模型理论基础与应用(七)
python·学习·ai·大模型·agent
流云鹤17 小时前
05Java学习day(5)
java·学习
only-lucky17 小时前
QML深入学习五(Controls模块)
前端·javascript·学习
Yolanda_202218 小时前
Python学习-第九部分-错误处理与异常处理
开发语言·python·学习