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;

相关推荐
Z21-X19 分钟前
云原生运维学习笔记:揭开虚拟化的硬核面纱,从底层架构到KVM实战
运维·笔记·学习·云原生
天疆说26 分钟前
DeepSeek 开源学习中心公开课调研笔记
笔记·学习·开源
艾莉丝努力练剑1 小时前
【AI大模型接入SDK】ChatServer 路由规则绑定
网络·c++·人工智能·学习·ai·架构
Rabitebla1 小时前
【Linux】 权限篇(三):深入理解 umask 位运算与粘滞位的设计思想
java·linux·服务器·c++·笔记·学习
誰能久伴不乏1 小时前
AI 时代,我们该怎么正确地学习编程
人工智能·学习
java_nnnn1 小时前
Linux 学习第一篇:从零认识 Linux,使用 WSL + Ubuntu 搭建学习环境
linux·运维·学习
实名上网宋凯宣2 小时前
现代电网可靠性测试系统-VPP工作笔记
笔记·学习
Z21-X2 小时前
云原生运维学习笔记:KVM实战——从环境搭建到热迁移的硬核体验
运维·笔记·学习·云原生
艾莉丝努力练剑2 小时前
【AI大模型接入SDK】Trae生成代码介绍
网络·c++·人工智能·学习·架构