【iOS開發系列】NSObject方法介紹

來源:互聯網
上載者:User

標籤:member   weight   int   運行   ase   對象   ber   more   val   

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方法介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.