Objective-C 处理动态类型的方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Objective-C 处理动态类型的方法相关的知识,希望对你有一定的参考价值。
方法 | 问题或行为 |
-(BOOL) isKindOfClass : class-object | 对象是不是class-object或其子类的成员 |
-(BOOL) isMemberOfClass:class-object | 对象是不是class-object的成员 |
-(BOOL) respondsToSelector:Selector | 对象是否能够响应selector所指定的方法 |
-(BOOL) instancesRespondToSelector | 指定的类实例是否能响应selector |
-(BOOL) isSubclassOfClass:class-object | 对象是否是指定类的子类 |
-(id) performSelector:selector | 应用selector指定的方法 |
-(id) performSelector:selector withObject:object | 应用selector指定的方法 |
-(id) performSelector:selector withObject:object1 withObject : object2 | 应用selector指定的方法 |
测试实验设计
继承关系图:
Rectangle.h
Square.h
在main.h中的测试如下:
// // main.m // Square // // Created by Apple on 2017/9/9. // Copyright 2017年 Apple. All rights reserved. // #import <Foundation/Foundation.h> #import "Square.h" int main(int argc, const char * argv[]) { @autoreleasepool { Square *mySquare = [[Square alloc] init]; //isMemberof if( [mySquare isMemberOfClass:[Square class]] == YES ) { NSLog(@" mySquare is a member of Square class ");// } if( [mySquare isMemberOfClass:[Rectangle class]] == YES ) { NSLog(@"mySquare is s member of Rectamgle class"); } if([mySquare isMemberOfClass:[NSObject class]] == YES) { NSLog(@"mySquare is a member of NSObject class"); } //isKindOf if( [mySquare isKindOfClass:[Square class]] == YES ) { NSLog(@" mySquare is a kind of Square class ");// } if( [mySquare isKindOfClass:[Rectangle class]] == YES ) { NSLog(@"mySquare is s kind of Rectamgle class"); } if([mySquare isKindOfClass:[NSObject class]] == YES) { NSLog(@"mySquare is a kind of NSObject class");// } //respondsTo: if( [mySquare respondsToSelector:@selector(setSide:)] == YES ) { NSLog(@" mySquare responds to setSide : method "); } if( [mySquare respondsToSelector:@selector(setWidth:addHeight:)] == YES ) { NSLog(@"mySquare responds to setWidth:addHeight : method"); } if([Square respondsToSelector:@selector(alloc)] == YES) { NSLog(@"Square class responds to alloc method"); } //instancesRespondTo: if( [Rectangle instancesRespondToSelector:@selector(setSide:)] == YES ) { NSLog(@"Instances of respond to setSide : method"); } if( [Square instancesRespondToSelector:@selector(setWidth:addHeight:)] == YES ) { NSLog(@"Instances of Square respond to setWidth:addHeight: : method"); } if([Square isSubclassOfClass:[Rectangle class]] == YES) { NSLog(@"Square is a subclass of a rectangle"); } return 0; } }
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1963970
以上是关于Objective-C 处理动态类型的方法的主要内容,如果未能解决你的问题,请参考以下文章
第9章 多态动态类型和动态绑定(Objective-C 程序设计)
Objective-C多态:动态类型识别+动态绑定+动态加载
如何将这个 Objective-C 代码片段写入 Swift?