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

相关推荐
d111111111d2 小时前
STM32中为什么会有APB1和APB2两个外设有什么区别
笔记·stm32·单片机·嵌入式硬件·学习
化作星辰3 小时前
深度学习_神经网络中最常用的学习率优化算法
深度学习·神经网络·学习
71-33 小时前
C语言练习题——判断水仙花数(0-100000)
c语言·笔记·学习
FAREWELL000753 小时前
Lua学习记录(3) --- Lua中的复杂数据类型_table
开发语言·学习·lua
Broken Arrows3 小时前
排查网络问题的一些工具的作用和常用使用方法
linux·网络·学习
雍凉明月夜5 小时前
Ⅱ人工智能学习之深度学习(deep-learning)概述
人工智能·深度学习·学习
d111111111d5 小时前
STM32外设学习--USART串口外设--学习笔记。
笔记·stm32·单片机·嵌入式硬件·学习
河铃旅鹿5 小时前
Android开发-java版:BroadcastReceiver广播
android·笔记·学习
洋洋的笔记6 小时前
小白银行测试初步了解(四)信用卡
经验分享·笔记·学习
im_AMBER6 小时前
HTTP概述 01
javascript·网络·笔记·网络协议·学习·http