IOS高階開發 Runtime(一)

2021-07-11 17:54:11 字數 2577 閱讀 4421

一些公用類:

@inte***ce customclass : nsobject

- (void) fun1;

@end

@implementationcustomclass

- (void) fun1

@end

@inte***ce testclass : nsobject

@end

@implementationtestclass

@end

別忘記引入庫:

#include

1、物件拷貝:

id object_copy(id obj, size_t size)

- (void) copyobj

列印結果:

2013-07-26 15:35:11.547 highoc[6859:c07] 0xbfffdf64

2013-07-26 15:35:11.547 highoc[6859:c07] 0xbfffdf60

2013-07-26 15:35:11.547 highoc[6859:c07] fun1

說明: object_copy 函式實現了物件的拷貝。

2、物件釋放id object_dispose(id obj)

- (void) objectdispose

列印結果:程式crash

malloc: *** error for object 0x758e6d0: pointer being freed was not allocated

3、更改物件的類/獲取物件的類

class object_setclass(id obj, class cls)  / 

class object_getclass(id obj)

- (void) setclasstest

- (void) getclasstest

4、獲取物件的類名

const

char *object_getclassname(id obj)

- (void) getclassname

5、給乙個類新增方法

bool class_addmethod(class cls,sel name,imp imp, 

const

char *types)

/*** 乙個引數 *

*/int cfunction(id

self, sel

_cmd, nsstring *str)

- (void) oneparam  else

int a = (int)[instanceocmethod:@"

我是乙個oc的

method,c

函式實現

"];nslog(@"a:%d", a);}

/*** 兩個引數 *

*/int cfunctiona(id

self, sel

_cmd, nsstring *str, nsstring *str1)

- (void) twoparam  else

inta = (

int)[instance

ocmethoda

:@"我是乙個oc的method,c函式實現":@"-----我是第二個引數"];

nslog(@"a:%d", a);

}相關文件及說明:

obj-c的方法(method)就是乙個至少需要兩個引數(self,_cmd)的c函式

imp有點類似函式指標,指向具體的method實現。

向乙個類動態新增方法

bool class_addmethod(class cls, sel name, imp imp, const char *types)

引數說明:

cls:被新增方法的類

name:可以理解為方法名

imp:實現這個方法的函式

types:乙個定義該函式返回值型別和引數型別的字串

class_addmethod([testclass class], @selector(ocmethod:), (imp)testfunc, "i@:@");

其中types引數為"i@:@「,按順序分別表示:

i:返回值型別int,若是v則表示void

@:引數id(self)

::sel(_cmd)

@:id(str)

官方文件:

頂0

IOS高階開發 Runtime(一)

一些公用類 inte ce customclass nsobject void fun1 end implementationcustomclass void fun1 end inte ce testclass nsobject end implementationtestclass end 別忘...

IOS高階開發 Runtime(三)

11 系統類的方法實現部分替換 void methodexchange 列印結果 仔細看log 2013 07 26 16 33 22.776 highoc 7104 c07 sssaaaass 2013 07 26 16 33 22.778 highoc 7104 c07 sssaaaass 12...

IOS高階開發 Runtime(三)

11 系統類的方法實現部分替換 void methodexchange 列印結果 仔細看log 2013 07 26 16 33 22.776 highoc 7104 c07 sssaaaass 2013 07 26 16 33 22.778 highoc 7104 c07 sssaaaass 12...