---
title: "ObjC Dynamic"
author: "xserver"
date: "2013-01-08T15:21:54Z"
tags: []
categories: ["编程语言"]
slug: "objc-dynamic"
draft: false
lastmod: "2013-06-09T13:50:29Z"
id: 1766266
url: "https://xserver.iteye.com/blog/1766266"
---

[原文](http://www.onevcat.com/2012/04/objective-c-runtime/)：http://www.onevcat.com/2012/04/objective-c-runtime/


动态类型（Dynamic typing）
动态绑定（Dynamic binding）
动态加载（Dynamic loading）

1、动态类型

而在实际使用中，往往使用introspection来确定该对象的实际所属类：


```java
id obj = someInstance;
if ([obj iskindofclass:someclass])
{
    someClass *classSpecifiedInstance = (someClass *)obj;
    // Do Something to classSpecifiedInstance which now is an instance of someClass
    //...
}
```

 

2、动态绑定
确定实例所属的类后，将某些属性和相应的方法绑定到实例上。
来确定对象是否可以对某个SEL做出响应。 

Special Considerations
This method is called before the Objective-C forwarding mechanism is invoked. If respondsToSelector: or instancesRespondToSelector: is invoked, the dynamic method resolver is given the opportunity to provide an IMP for the given selector first.


```java
void dynamicMethodIMP(id self, SEL _cmd)
{
    // implementation ....
}
 
//该方法在OC消息转发生效前被调用
+ (BOOL) resolveInstanceMethod:(SEL)aSEL
{
    if (aSEL == @selector(resolveThisMethodDynamically))
    {
          //向[self class]中新加入返回为void的实现，SEL名字为aSEL，实现的具体内容为dynamicMethodIMP
          class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, &quot;v@:&quot;);
          return YES;
    }
    return [super resolveinstancemethod:asel];
}
```


3、动态加载

**根据参数，动态地加载资源……**

```java
-(NSArray *)loadPadNibNamed:(NSString *)name owner:(id)owner options:(NSDictionary *)options 
{
NSString *newName = [name stringbyreplacingoccurrencesofstring:@&quot;@pad&quot; withstring:@&quot;&quot;];
newName = [newname stringbyappendingformat:@&quot;@pad&quot;];
 
//判断是否存在
NSFileManager *fm = [nsfilemanager defaultmanager];
NSString* filepath = [[nsbundle mainbundle] pathForResource:newName ofType:@&quot;nib&quot;];
 
//这里调用的loadPadNibNamed:owner:options:实际为为交换后的方法，即loadNibNamed:owner:options:
if ([fm fileexistsatpath:filepath]) {
return [self loadpadnibnamed:newname owner:owner options:options];
} else {
return [self loadpadnibnamed:name owner:owner options:options];
}
}
```



```java

//OC
Class c = NSClassFromString(@"Name");
//Java，忘光了～
Class c = Class.forName("Name");
URLClassLoader

```



NSClassFromString的好处是：
1 弱化连接，因此并不会把没有的Framework也link到程序中。
2 不需要使用import，因为类是动态加载的，只要存在就可以加载。因此如果你的toolchain中没有某个类的头文件定义，而你确信这个类是可以用的，那么也可以用这种方法。

<http://superart.wikidot.com/chinese:iphone-nsclassfromstring>
－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－


```java

	SEL selfunc = NSSelectorFromString(NSString *str); //方法名称
	if ([object respondstoselector:selfunc]) { //判断方法是否存在
		[object performselector:selfunc]; //执行方法

```



一开始感觉不出有什么用，直接传对象或者protocol就可以了。
这样能更放荡，用的所谓的oo思想，把所有对象都抽象为Object，
和上面的NSClassFromString是一种思想，从具象到相对抽象

用来做回调：<http://www.wuleilei.com/blog/263>
－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－




```java

#import <objc/runtime.h>  //重点
NSString *str;  
Mobj *obj = [[mobj alloc] init];  //Mobj中有一私有属性NSString *mt_; 
object_getInstanceVariable(obj, "mt_", (void *)&str);  
NSLog(@"%@",str);    
[obj release]; 
```

来至：<http://my.oschina.net/rareliu/blog/32022?catalog=86431>