如何在运行时动态地将id标记为具体类? [英] How to typecast an id to a concrete class dynamically at runtime?
问题描述
我有几个数据源我用于一个UIViewController。我的视图控制器使用KeyValue观察以跟踪某些属性在运行时的状态。当我交换dataSources时,我需要停止观察这些属性。问题是,我不知道在运行时的dataSource的类,因此这样的东西是无效的:
I have several dataSources I use for one UIViewController. My view controller uses KeyValue Observing in order to follow the state of certain properties at runtime. When I swap dataSources, I need to stop observing those properties. The problem is, I'm not sure of the class of the dataSource at runtime, therefor something like this is not valid:
if (aDataSource != dataSource) {
// Ensure we stop observing the existing dataSource, otherwise bad stuff can happen.
[dataSource removeObserver:self forKeyPath:@"someKeyPath"]; // not valid, compiler doesn't know what class dataSource is.
[dataSource release];
dataSource = [aDataSource retain];
}
编译器需要一个具体的类才能知道对象的接口。在这种情况下,如何获取dataSource的类,然后为上面的removeObserver:forKeyPath:selector输入dataSource?我喜欢动态/更聪明的方法比在NSString实例中缓存类的名称,并且每当我切换时引用。意思是,我总是可以这样做:
The compiler needs a concrete class in order to know the object's interface. How can I grab the class of dataSource in this particular case, and then typcast the dataSource for the removeObserver:forKeyPath: selector above? I prefer something dynamic/smarter than caching the name of the class in an NSString instance and referring to that whenever I switch. Meaning, I could always do something like:
NSString *lastDataSource = @"MyClass";
Class foo = [NSClassFromString(lastDataSource)];
谢谢。
推荐答案
-
如果你这样编码:
If you code like this:
id foo = ...;
[foo removeObserver:self forKeyPath:@"someKeyPath"];
编译器会正常处理类型为 id $
The compiler will be fine with it as objects with type id
accepts any message (as long the signature is known to the compiler).
现在如果你有:
id<NSObject> foo = ...;
[foo removeObserver:self forKeyPath:@"someKeyPath"];
编译器会给你一个警告:
The compiler will give you a warning:
警告:'-removeObserver:forKeyPath:'在协议中找不到
warning: '-removeObserver:forKeyPath:' not found in protocol
但是如果你有:
NSObject* foo = ...;
[foo removeObserver:self forKeyPath:@"someKeyPath"];
这将编译正常,因为在这种情况下你使用NSObject类。
That will compile fine too, as in this case you're using the class NSObject.
相关链接:
- a href =http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-SW1 =nofollow noreferrer>目标-C protocol
- ID类型和协议
- Objective-C protocol
- The id Type and Protocols
这篇关于如何在运行时动态地将id标记为具体类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!