This article combines my project experience and income

New project is written by Swift, new thing used really can’t quit, but mixed with OC is the most deadly…

Take a chestnut

In our project, we used the third-party IM service (basically all the libraries and codes provided by the third-party IM service in the market are also OC), so the pit came to us. The situation is as follows:

NSString *contentStr = [layoutConfig cellContent:self.model]; Class clazz = NSClassFromString(contentStr); / / string Class NIMSessionMessageContentView * contentView = [[clazz alloc] initSessionMessageContentView]; NSAssert(contentView, @"can not init content view");
Copy the code

To paraphrase, this im-UI library code creates a contentView class from a string in the Model.

For example: IM – in the UI library of OC class NIMSessionLocationContentView. H, contentStr = @ “NIMSessionLocationContentView” and get the corresponding clazz NIMSessionLocationContentView.

Because it is a Swift project and the custom contentView class, we have our Swift file contentView -> CDNetCallTipContentView. So the problem is, contentStr = @”CDNetCallTipContentView” is fine, but clazz is nil.

After checking, this kind of mixed situation to specify the namespace! The namespace is the Target name of its own project. For example, Target is CDApp. The OC file for correct CDNetCallTipContentView way is ` contentStr = @ “CDApp. CDNetCallTipContentView”.

But the problem is not completely solved!

Many of you have multiple targets in your project because you need them (for development version or environment reasons). For example, the original Target is CDApp, the development environment’s CDApp Dev. There are Spaces among the development environment of the Target name, at that time if contentStr = @ “CDApp Dev. CDNetCallTipContentView”, finally clazz is nil. In space, the way to put Spaces replace single underscore _ contentStr = @ “CDApp_Dev. CDNetCallTipContentView”.

Here is the modified code:

NSString *contentStr = [layoutConfig cellContent:self.model];
Class clazz = NSClassFromString(contentStr);
if(! clazz){ NSString * nameSpace = [NSBundle mainBundle].infoDictionary[@"CFBundleName"];
    contentStr = [[NSString stringWithFormat:@"% @ % @",nameSpace,contentStr] stringByReplacingOccurrencesOfString:@"" withString:@"_"]; Clazz = NSClassFromString(contentStr); } NIMSessionMessageContentView *contentView = [[clazz alloc] initSessionMessageContentView]; NSAssert(contentView, @"can not init content view");
Copy the code