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 <Foundation/Foundation.h>
@class Button;

#pragma mark <>代表protocol
@protocol StudyProtocol <NSObject>

- (void)onClick:(Button *)btn;

@end

//

// Button.h

//

#import <Foundation/Foundation.h>

@protocol StudyProtocol;

@interface Button : NSObject

@property (nonatomic,retain) id<StudyProtocol> delegate;

  • (void)testClick;

@end

//

// Button.m

//

#import <Foundation/Foundation.h>

#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 <Foundation/Foundation.h>

#import "StudyProtocol.h"

NS_ASSUME_NONNULL_BEGIN

@interface ButtonListener : NSObject <StudyProtocol>

@end

NS_ASSUME_NONNULL_END

//

// ButtonListener.m

//

#import <Foundation/Foundation.h>

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

相关推荐
新手unity自用笔记29 分钟前
项目-坦克大战学习笔记-按键按下控制方向
笔记·学习·c#
瞌睡不来41 分钟前
(刷题记录5)盛最多水的容器
c++·笔记·学习·题目记录
一 乐1 小时前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·数据库·学习·考研·微信·小程序·源码
William_Edmund2 小时前
C++ 算法学习——1.8 悬线法
学习
朝九晚五ฺ2 小时前
【Linux探索学习】第三弹——Linux的基础指令(下)——开启新篇章的大门
linux·运维·学习
IM_DALLA2 小时前
【Verilog学习日常】—牛客网刷题—Verilog企业真题—VL74
学习·fpga开发·verilog学习
王俊山IT3 小时前
C++学习笔记----8、掌握类与对象(五)---- 嵌套类与类中枚举
开发语言·c++·笔记·学习
北极无雪3 小时前
Spring源码学习(拓展篇):SpringMVC中的异常处理
java·开发语言·数据库·学习·spring·servlet
问道飞鱼4 小时前
每日学习一个数据结构-默克尔树(Merkle Tree)
数据结构·学习·默克尔树
William_Edmund4 小时前
Python 语言学习——应用1.2 数字图像处理(第二节,变换)
人工智能·学习·计算机视觉