0

In objective C, a Category will only "be used" in a class if I import it. So if I have a Category NSString+category, I have to #import NSString+category.h in each class I want to use it.

I have such a Category, and some of the classes I want to use it in are written in Swift. If I expose this category to Swift by putting it in the Bridging header, ALL swift classes will use it. How can this be avoided?

Note: My Category is actually on UIViewController and the code I have put there must only be used by SOME ViewControllers. It feels wrong and unneccessary to use this Category on the "other" ViewControllers.

Joakim
  • 3,224
  • 3
  • 29
  • 53
  • 3
    "In objective C, a Category will only "be used" in a class if I import it." This isn't true; the methods from the category are always present on the class. The header only provides _visibility_: you'll get a compiler error if you try to call them without the import. – jscs Nov 29 '16 at 16:59
  • Aha. My bad. I guess that effectively answers my question. – Joakim Nov 30 '16 at 08:27
  • Can you show the code? Also I created full tutorial to use Swift and Objective-c together. http://stackoverflow.com/a/40887287/4488252 – Vasily Bodnarchuk Dec 01 '16 at 17:49

1 Answers1

2

Your base assumption is incorrect:

In objective C, a Category will only "be used" in a class if I import it

The methods in a category are present on the class if the category is compiled. Importing the header makes the method names visible; without that the compiler will give you a warning if you try to send a message using one of those names. (You can call the methods using performSelector: or the runtime library if you're determined.)

The same is true of your Swift class, and because of the way Objective-C headers are brought in to Swift, I don't believe there's a way to limit the methods' visibility in your Swift code.

jscs
  • 63,694
  • 13
  • 151
  • 195