How to typify an identifier for a particular class dynamically at runtime?

I have several data sources that I use for one UIViewController. The My view controller uses KeyValue Observing to track the state of certain properties at runtime. When I replace dataSources, I need to stop observing these properties. The problem is that I'm not sure about the dataSource class at runtime, so 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];
}

The compiler needs a specific class to know the interface of the object. How can I grab the dataSource class in this particular case and then the typcast dataSource for removeObserver: forKeyPath: selector above? I prefer something dynamic / smarter than caching the class name in an NSString instance and referring to this every time I switch. Meaning, I could always do something like:

NSString *lastDataSource = @"MyClass";
Class foo = [NSClassFromString(lastDataSource)];

Thank.

+2
source share
4 answers
  • If you code is:

    id foo = ...;
    [foo removeObserver:self forKeyPath:@"someKeyPath"];
    

    The compiler will be fine with it, since objects of type idaccept any message (as long as the signature is known to the compiler).

  • Now if you have:

    id<NSObject> foo = ...;
    [foo removeObserver:self forKeyPath:@"someKeyPath"];
    

    The compiler will give you a warning:

    warning: '-removeObserver: forKeyPath:'

    , NSObject NSObject, KVO.

  • :

    NSObject* foo = ...;
    [foo removeObserver:self forKeyPath:@"someKeyPath"];
    

    , NSObject.

:

+6

, ? ?

Objective-C . Objective-C, , .

+2

, NSObject *, KVO ( NSObject).

+1

, , ...

NSString *lastDataSource = @"MyClass";
Class foo = [NSClassFromString(lastDataSource)];

..., , , "foo" . , , , , "foo" "MyClass", , , "MyClass" "myMethod:", , , "foo" .

, , , .

+1

Source: https://habr.com/ru/post/1739866/


All Articles