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

相关推荐
eggcode1 小时前
IDEA与Maven使用-学习记录(持续补充...)
学习·maven·intellij-idea
charlie1145141913 小时前
从0开始的操作系统手搓教程33:挂载我们的文件系统
学习·系统架构·操作系统·教程·文件系统·手搓教程
雨墨C4 小时前
LLM学习之路-01-第一章-预训练/搞懂大模型的分词器(二)
人工智能·学习·自然语言处理·chatgpt·大模型·transformer
skywalk81634 小时前
OWL(Optimized Workforce Learning): 优化劳动力学习的通用智能体,用于处理现实世界的自动化任务(58.18 平均分)
人工智能·学习·自动化·agent
charlie1145141914 小时前
IMX6ULL驱动开发uboot篇02
驱动开发·学习·操作系统·内核·教程·uboot
李匠20245 小时前
c++学习之QT综合项目一
学习
windwant6 小时前
机器学习之监督学习
人工智能·学习·机器学习
IT、木易7 小时前
React 学习全阶段总结
javascript·学习·react.js
charlie1145141919 小时前
从0开始的操作系统手搓教程43——实现一个简单的shell
学习·操作系统·教程·shell·手搓教程