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;

相关推荐
马***4117 小时前
适配成人英语学习痛点,打造落地性强的学习辅助方式
人工智能·学习
小拉达不是臭老鼠9 小时前
Unity学习_ScriptableObject
学习·unity
MartinYeung510 小时前
[论文学习]LLM 与其他 AI 模型的隐私考量:输入与输出隐私框架方法
人工智能·学习
(●—●)橘子……11 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
AOwhisky12 小时前
MySQL 学习笔记(第一期):数据库基础与 MySQL 初探
运维·数据库·笔记·学习·mysql·云计算
try2find13 小时前
Agent学习之补充my_plan_solve_agent
学习
想你依然心痛14 小时前
HarmonyOS 6(API 23)实战:打造“光码智学舱“——AI编程学习新范式
学习·ar·ai编程·harmonyos·智能体
一口吃俩胖子15 小时前
【脉宽调制DCDC功率变换学习笔记023】渐进分析法
笔记·学习
m0_3771081415 小时前
pid学习
学习
爱喝水的鱼丶15 小时前
SAP-ABAP:SAP基础数据校验工具开发系列博客(共5篇)第三篇:SAP接口对接开发:实现数据的实时/批量校验交互
运维·数据库·学习·性能优化·sap·abap·经验交流