Inability to create my CIFilter classes from strin

2019-09-06 21:11发布

问题:

After creating this question myself about the inability to create my own UIImageView classes by name I am facing a similar problem, this time for CIFilter subclasses that are not solved by the accepted answer on the other question.

Said that, this is the problem.

I am creating subclasses of CIFilter class, something like MyEffectFilter1, MyEffectFilter1, etc.

These subclasses have this convenience method for the creation of specific images:

+ (instancetype)novo {
   MyEffectFilter1 * newFilter = [self filterWithName:...
   // do stuff
   return newFilter;
 }

When I try to create such classes using this new command by string

id newObject = [NSClassFromString(nameOfClass) novo];

And verify the created objects, I see that their classes are not the ones I create but CIFilter ones. For example: if I create a Comic filter using my created class:

// initialization code on MyComicClass.m
+ (instancetype)novo {
   MyComicClass * newFilter = [self filterWithName:@"CIComicEffect"];
   // do stuff
   return newFilter;
 }

By doing

id newObject = [NSClassFromString(@"MyComicClass") novo];

and do a po newObject to console, or test the class using

Class class = [newObject class];

I get class equal to CIComicEffect not MyComicClass.

Any ideas on how to solve this?

回答1:

In this case, the subclass constructor is trying to call the inherited class's convenience constructor (in contrast with the previous question, which was calling the inherited init).

Change your constructor to do the analogous thing, calling alloc on self. It doesn't look like CIFilter provides any public initWith... methods, but a property such as name can be set easily enough by calling the new instance directly...

// MyEffectFilter1.m
+ (instancetype)novo {
    MyEffectFilter1 *newFilter = [[self alloc] init];
    newFilter.name = @"name";
    return newFilter;
}

I tested that code as follows...

MyEffectFilter1 *filterA = [MyEffectFilter1 novo];
MyEffectFilter1 *filterB = [NSClassFromString(@"MyEffectFilter1") novo];

In lldb, these inspect as follows...