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

相关推荐
SPFFC189380330531 天前
AI玩具排线专业生产与全球营销策略
人工智能·学习·智能手机·显示器·智能手表·平板·游戏机
。TAT。1 天前
C++ - vector
开发语言·c++·学习
YJlio1 天前
Process Monitor 学习笔记(5.7):长时间运行追踪与日志文件体积的控制
java·笔记·学习
派森先生1 天前
sk09.【scikit-learn基础】--『无监督学习』之K均值聚类
学习·均值算法·scikit-learn
JJJJ_iii1 天前
【机器学习03】学习率与特征工程、多项式回归、逻辑回归
人工智能·pytorch·笔记·学习·机器学习·回归·逻辑回归
_dindong1 天前
Linux网络编程:Socket编程预备
linux·运维·网络·学习
deng-c-f1 天前
Linux C/C++ 学习日记(25):KCP协议:普通模式与极速模式
linux·学习·kcp
_dindong1 天前
Linux网络编程:宏观网络体系
linux·网络·笔记·学习
碱化钾1 天前
学习笔记——GPU训练
笔记·学习
派森先生1 天前
sk08.【scikit-learn基础】--『监督学习』之K近邻算法
学习·scikit-learn·近邻算法