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

相关推荐
行者游学22 分钟前
ETCD 学习使用
数据库·学习·etcd
Python私教1 小时前
Unity 游戏开发「工业化级」学习路线 2025 版
学习·unity·游戏引擎
charlie1145141912 小时前
2D 计算机图形学基础速建——2
笔记·学习·线性代数·教程·计算机图形学
勇往直前plus3 小时前
学习和掌握RabbitMQ及其与springboot的整合实践(篇二)
spring boot·学习·rabbitmq·java-rabbitmq
py有趣4 小时前
LeetCode算法学习之杨辉三角
学习·算法·leetcode
具身新纪元4 小时前
现代机器人学习入门:一份来自Hugging Face与牛津大学的综合教程开源SOTA资源库
学习·机器人
~无忧花开~4 小时前
掌握Axios:前端HTTP请求全攻略
开发语言·前端·学习·js
敲代码的嘎仔5 小时前
JavaWeb零基础学习Day5——MySQL
java·数据库·学习·程序人生·mysql·adb·改行学it
老师可可6 小时前
成绩发布工具使用方法,附成绩分析教程
学习·信息可视化·小程序·excel·学习方法
阿民不加班7 小时前
【React】打卡笔记,入门学习02:react-router
笔记·学习·react.js