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\];

相关推荐
iFulling10 小时前
【计算机网络】第四章:网络层(上)
学习·计算机网络
香蕉可乐荷包蛋11 小时前
AI算法之图像识别与分类
人工智能·学习·算法
xiaoli232711 小时前
课题学习笔记1——文本问答与信息抽取关键技术研究论文阅读(用于无结构化文本问答的文本生成技术)
笔记·学习
人生游戏牛马NPC1号11 小时前
学习 Flutter (四):玩安卓项目实战 - 中
android·学习·flutter
LGGGGGQ12 小时前
嵌入式学习-PyTorch(7)-day23
人工智能·pytorch·学习
stm 学习ing13 小时前
Python暑期学习笔记3
笔记·python·学习
屁股割了还要学13 小时前
【C语言进阶】内存函数
c语言·开发语言·学习·算法·青少年编程
靴子学长13 小时前
Lotus-基于大模型的查询引擎 -开源学习整理
python·学习·自然语言处理
Littlewith14 小时前
Node.js:创建第一个应用
服务器·开发语言·后端·学习·node.js
ROOKIE Shawn14 小时前
mysql学习笔记
笔记·学习