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;

相关推荐
AAA@峥13 分钟前
系统化学习 MySQL:数据类型、库表管理、增删改查全解析
数据库·学习·mysql
GeekArch12 小时前
第28讲:避坑——AI堆栈分配错误、栈溢出BUG
c语言·人工智能·stm32·mcu·学习·bug
weixin_4280053013 小时前
C#调用 AI学习从0开始-第3阶段RAG向量数据库-文档切分与入库第15天
人工智能·学习·c#·向量数据库·rag·qdrant·文档切分与入库
dankokoko14 小时前
一.函数与极限2
学习
知识分享小能手15 小时前
统计学学习教程,从入门到精通,分类数据分析 — 知识点详解(14)
学习·分类·数据分析
菜鸟‍15 小时前
【论文学习】MICCAI 2025 || ARSeg:面向不完整文本提示的鲁棒医学图像指代表达分割
图像处理·学习
三克的油15 小时前
c++算法学习-4
学习
知识分享小能手16 小时前
统计学学习教程,从入门到精通,分类数据分析 — 知识点详解(13)
学习·分类·数据分析
大龄秃头程序员17 小时前
揭秘 KVC 底层:Objective-C KVC 究竟依赖了哪些 Runtime 能力
objective-c
大龄秃头程序员17 小时前
Objective-C 浅拷贝与深拷贝:从踩坑到彻底搞懂
objective-c