Objective-c SEL & Class IMP

來源:互聯網
上載者:User
ObjC(Objective-C)中的Class(類類型),Selector(選取器SEL),函數指標(IMP) 今天在園子裡看到了一篇牛文“ Objective-C 2.0 with Cocoa Foundation--- 5,Class類型,選取器Selector以及函數指標 ”,講得十分精彩,忍不住把它的代碼加上注釋整理於此,以便日後查看。 個人體會:obj-C中的“Class類型變數”比c#中的Object基類還要靈活,可以用它產生任何類型的執行個體(但是它又不是 NSObject)。而選取器SEL與函數指標IMP,如果非要跟c#扯上關係的話,這二個結合起來,就點類似c#中的反射+委託,可以根據一個方法名稱字串,直接調用方法。 "牛"的基類 Cattle.h view source print ?
1 #import <Foundation/Foundation.h>
2   
3 @interface Cattle : NSObject {
4     int legsCount;
5 }
6 - (void)saySomething;
7 - (void)setLegsCount:(int) count;
8 @end
Cattle.m view source print ?
01 #import "Cattle.h"
02   
03 @implementation Cattle
04   
05 -(void) saySomething
06 {
07     NSLog(@"Hello, I am a cattle, I have %d legs.", legsCount);
08 }
09   
10 -(void) setLegsCount:(int) count
11 {
12     legsCount = count;
13 }
14 @end
子類“公牛" Bull.h view source print ?
01 #import <Foundation/Foundation.h>
02 #import "Cattle.h"
03   
04 @interface Bull : Cattle {
05     NSString *skinColor;
06 }
07 - (void)saySomething;
08 - (NSString*) getSkinColor;
09 - (void) setSkinColor:(NSString *) color;
10 @end
Bull.m view source print ?
01 #import "Bull.h"
02   
03   
04 @implementation Bull
05   
06 -(void) saySomething
07 {
08     NSLog(@"Hello, I am a %@ bull, I have %d legs.", [self getSkinColor],legsCount);
09 }
10   
11 -(NSString*) getSkinColor
12 {
13     return skinColor;
14 }
15   
16 - (void) setSkinColor:(NSString *) color
17 {
18     skinColor = color;
19 }
20 @end
代理類DoProxy.h (關鍵的代碼都在這裡) view source print ?
01 #import <Foundation/Foundation.h>
02   
03 //定義幾個字串常量
04 #define SET_SKIN_COLOR @"setSkinColor:"
05 #define BULL_CLASS @"Bull"
06 #define CATTLE_CLASS @"Cattle"
07   
08   
09 @interface DoProxy : NSObject {
10     BOOL notFirstRun;
11       
12     id cattle[3];
13     //定義二個選取器
14     SEL say;
15     SEL skin;
16       
17     //定義一個函數指標(傳統C語言的處理方式)
18     void(*setSkinColor_Func)(id,SEL,NSString*);
19       
20     //定義一個IMP方式的函數指標(obj-C中推薦的方式)
21     IMP say_Func;
22       
23     //定義一個類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.