陈斌彬的技术博客

Stay foolish,stay hungry

OC-NSObject方法介绍

NSObject是OC中的基类,所有类都继承于此,这里面也给我们提供了很多与“类”和“方法”相关的方法,本文将讲解几个非常实用的方法。

正文:

Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject 
@end

Student.h

#import "Person.h"

// 继承Person类
@interface Student : Person 

- (void)test1; 
- (void)test2:(NSString *)string; 

@end

MyProtocol.h

#import <Foundation/Foundation.h>

@protocol MyProtocol  
@end

1. 判断student是否是Person类的对象

// - (BOOL)isMemberOfClass:(Class)aClass;        
[student isMemberOfClass:[Person class]];

2. 判断student是否是Person类或子类的对象

// - (BOOL)isKindOfClass:(Class)aClass;        
[student isKindOfClass:[Person class]];

3. 判断student是否遵循MyProtocol协议(也可以用类调用,判断该类是否遵循)

// - (BOOL)conformsToProtocol:(Protocol *)aProtocol;        
[student conformsToProtocol:@protocol(MyProtocol)];      

// 或者使用类方法        
// + (BOOL)conformsToProtocol:(Protocol *)protocol;        
[Student conformsToProtocol:@protocol(MyProtocol)];

4. 判断student的test1方法是否响应(即:是否声明并实现了test1方法)

// - (BOOL)respondsToSelector:(SEL)aSelector;        
[student respondsToSelector:@selector(test1)];

5. 间接调用student的test1方法(test1无参数)

// - (id)performSelector:(SEL)aSelector;        
[student performSelector:@selector(test1)];

6. 间接调用student的test2方法(test2有一个参数)

// - (id)performSelector:(SEL)aSelector withObject:(id)object;        
[student performSelector:@selector(test2:) withObject:@"123"];      

// 最多带两个参数        
//- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

7. 延迟2s调用student的test1方法

(在命令行没有延迟效果,因为命令行执行完后就退出main函数了 ,在IOS部分main函数一直在执行,所以可以看到延迟效果)

// - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;        
// delay单位为(秒)        
[student performSelector:@selector(test2:) withObject:@"123" afterDelay:2];