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

相关推荐
今天也好累3 小时前
C语言安全格式化:snprintf核心指南
c语言·笔记·学习·visual studio
崇山峻岭之间4 小时前
Matlab学习记录18
开发语言·学习·matlab
玄同7657 小时前
我是如何开发项目的?——从 “踩坑思维” 到 “工程化能力”:编程学习的进阶方法论(万字版)
开发语言·人工智能·经验分享·笔记·python·学习·课程设计
●VON7 小时前
影像之眼:人工智能如何重塑医学诊断的边界
人工智能·学习·von
暗流者7 小时前
ctf wiki中kernel pwn 学习编译内核(2026年最新版)
学习·安全·网络安全·pwn
深蓝海拓7 小时前
PySide6之QListWidget 学习
笔记·python·qt·学习·pyqt
末日汐7 小时前
linux--进程学习
linux·运维·服务器·学习
A9better7 小时前
嵌入式开发学习日志46——FreeRTOS之列表与列表项
学习
2301_781143567 小时前
联考——言语理解与表达笔记(一)
笔记·学习·考公
运维帮手大橙子7 小时前
从基础到体系:我的年度技术学习与实战总结
经验分享·学习