首页 > 代码库 > 【iOS开发系列】NSObject方法介绍

【iOS开发系列】NSObject方法介绍

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


正文:


Person.h

#import <Foundation/Foundation.h>
@interface Person : NSObject 
@end</span>

Student.h

#import "Person.h"
// 继承Person类
@interface Student : Person 
- (void)test1; 
- (void)test2:(NSString *)string; 
@end</span>

MyProtocol.h

#import <Foundation/Foundation.h>
@protocol MyProtocol  
@end</span>

【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函数一直在运行。所以能够看到延迟效果)

<span style="font-family:SimHei;">// - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;  
// delay单位为(秒)        
[student performSelector:@selector(test2:) withObject:@"123" afterDelay:2];</span>

【iOS开发系列】NSObject方法介绍