Search code examples
objective-cswiftstatic-librariesobjective-c-swift-bridgeclass-extensions

Could I extend NSString class in Static Library and use it in App with Swift?


I extend NSString in my custom static library CommonLib :

//NSString+ext.h
#import <Foundation/Foundation.h>

@interface NSString (ext)
- (BOOL)isContainsEmoji;
@end



//NSString+ext.m
#import "NSString+ext.h"

@implementation NSString (ext)
- (BOOL)isContainsEmoji{
    //Do Something...
}
@end

Because CommonLib contains some Swift code files ,so I create a bridging header file CommonLib-Bridging-Header.h in CommonLib project:

//in CommonLib-Bridging-Header.h
#import "NSString+ext.h"

Next,I link CommonLib to my App project,and create a new file Node.swift in App project:

//Node.swift
import Foundation
import CommonLib

class Node{

    var name:String!
    var isBadName:Bool{
        let tmpString = name as NSString
        return tmpString.isContainsEmoji()
    }
}

Last,I use it somewhere in my App:

//In my UIViewController class
override func viewDidAppear(...){
    super.viewDidAppear(...)

    let node = Node()
    node.name = "panda hopy"
    print("\(node.isBadName)") //Crash in this line!!!
}

At this time compile is OK!!! But when I run App it's Crashed:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Swift._NSContiguousString isContainsEmoji]: unrecognized selector sent to instance 0x60400084b340'

So is something wrong here??? And how to fix it??? Thanks ;)

(PS:my environment Xcode 9.3.1 swift 4.1)


Solution

  • Finally, I'm glad to fixed this Q ;)

    It's very easy, add link option to App project :

    -all_load

    That's all right ,you can refer to this :

    unrecognized selector sent to instance” to a static library despite ObjC flag

    Thanks everyone ;)