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;

相关推荐
通信小呆呆16 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick16 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee16 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn8616 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e16 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨16 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
cqbzcsq16 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
YangYang9YangYan16 天前
2026初入职场学习数据分析的价值
学习·数据挖掘·数据分析
guslegend16 天前
理论学习:什么是 Coding Agent?
学习
自传.16 天前
尚硅谷 Vibe Coding|第三章(1) Claude Code深度使用与进阶技巧 学习笔记
笔记·学习·尚硅谷·vibecoding