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

相关推荐
大白的编程日记.5 分钟前
【计算机基础理论知识】C++篇(二)
开发语言·c++·学习
Chef_Chen7 分钟前
从0开始学习R语言--Day42--LM检验
学习
C语言小火车11 分钟前
野指针:C/C++内存管理的“幽灵陷阱”与系统化规避策略
c语言·c++·学习·指针
Chef_Chen22 分钟前
从0开始学习R语言--Day40--Kruskal-Wallis检验
开发语言·学习·r语言
ozawacai1 小时前
markdown学习笔记(个人向) Part.1
笔记·学习
吃货界的硬件攻城狮1 小时前
【显示模块】嵌入式显示与触摸屏技术理论
stm32·单片机·嵌入式硬件·学习
rui锐rui2 小时前
大数据学习6:Sqoop数据迁移工具
大数据·学习·sqoop
psybrain2 小时前
脑科学圈| 利用眼动追踪评估演讲情境下焦虑障碍儿童的注视行为
学习·心理学·脑科学·课堂·焦虑·儿童青少年·眼动
序属秋秋秋3 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
许白掰3 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器