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 \ @class Button;** **#pragma mark \<\>代表protocol @protocol StudyProtocol \** **- (void)onClick:(Button \*)btn;** **@end** // // Button.h // #import \ @protocol StudyProtocol; @interface Button : NSObject @property (nonatomic,retain) id\ delegate; - (void)testClick; @end // // Button.m // #import \ #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 \ #import "StudyProtocol.h" NS_ASSUME_NONNULL_BEGIN @interface ButtonListener : NSObject \ @end NS_ASSUME_NONNULL_END // // ButtonListener.m // #import \ #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 alloc\]init\]; //设置监听器 \[btn setDelegate: listener\]; //模拟点击 \[btn testClick\];

相关推荐
2501_941145851 小时前
虚拟现实与增强现实技术在教育培训与沉浸式学习场景中的创新应用研究
学习·ar·vr
inputA1 小时前
【LwIP源码学习8】netbuf源码分析
android·c语言·笔记·嵌入式硬件·学习
d111111111d1 小时前
STM32外设学习-I2C(细节)--学习笔记
笔记·stm32·单片机·嵌入式硬件·学习
( ˶˙⚇˙˶ )୨⚑︎1 小时前
【学习笔记】DiffFNO: Diffusion Fourier Neural Operator
笔记·神经网络·学习
Topplyz1 小时前
交流耦合同相放大电路、MAX4466音频放大电路功能详解
学习·运算放大器·模电·放大电路·音频放大
ModestCoder_2 小时前
【学习笔记】Diffusion Policy for Robotics
论文阅读·人工智能·笔记·学习·机器人·强化学习·具身智能
麦麦大数据2 小时前
F049 知识图谱双算法推荐在线学习系统vue+flask+neo4j之BS架构开题论文全源码
学习·算法·知识图谱·推荐算法·开题报告·学习系统·计算机毕业设计展示
李绍熹2 小时前
半监督对比学习 (Semi-Supervised SimCLR) 实现
学习
952362 小时前
数据结构-堆
java·数据结构·学习·算法
im_AMBER3 小时前
Leetcode 57
笔记·学习·算法·leetcode