object-c的id

來源:互聯網
上載者:User

Objective-C裡面的特殊類型,用來指向物件類型,有點類似與c語言的(void *)。關鍵字nil用來表示c語言的null.
有了id,使用者在調用一個對象的方法時,就可以不必知道這個對象具體是什麼類型。執行個體如下:
1. 代碼:
//ClassA.h
#import <Foundation/NSObject.h>
@interface ClassA: NSObject 
-(void) print;
@end

//ClassA.m
#import "ClassA.h"
@implementation ClassA

-(void) print {
    printf( "this is ClassA\n");
}
@end

//ClassB.h
#import <Foundation/NSObject.h>

@interface ClassB: NSObject 

-(void) print;
@end

//ClassB.m
#import "ClassB.h"

@implementation ClassB

-(void) print {
    printf( "this is ClassB\n");
}
@end

//main.m

#import <stdio.h>
#import "ClassA.h"
#import "ClassB.h"

int main( int argc, const char *argv[] ) {
    // create  instance
    ClassA *a = [[ClassA alloc] init];
    ClassB *b = [[ClassB alloc] init];
    id number;

    // print 
    number = a;
    [number print];
    printf( "\n" );
    
    // print 
    number = b;
    [number print];
    printf( "\n" );
}

2. 編譯和運行:
gcc -fconstant-string-class=NSConstantString -c main.m -I /GNUstep/System/Library/Headers
gcc -c ClassA.m -I /GNUstep/System/Library/Headers
gcc -c ClassB.m -I /GNUstep/System/Library/Headers
gcc main.o ClassA.o ClassB.o -o main -L /GNUstep/System/Library/Libraries/ -lobjc -lgnustep-base

$ ./main.exe
this is ClassA

this is ClassB

3.說明:
   (1)系統總是能找到id的正確類型。
   (2)這種方法和C++,java中的類型轉換有異曲同工之妙,但是卻是完全不同的概念和實現原理。

聯繫我們

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