Weak link My own Objective-C Class

Is it possible to put together my own objective-c classes?

I saw that I can loosely bind a function or variable ...

extern int MyFunction() __attribute__((weak_import)); extern int MyVariable __attribute__((weak_import)); 

I would like to have something like this ...

 if ([MyUploadManager class]) { self.uploadButton.hidden = NO; } 

... and be able to compile even if UploadManager.m is not included in the project.

+6
source share
3 answers

To a weak class mix, for example. MyUploadManager in your own executable:

  • To keep the linker happy, add it to Other Linker Flags in the project:

     -Wl,-U,_OBJC_CLASS_$_MyUploadManager 

    This allows the class symbol to be undefined, even if it is not embedded in your executable. Instead, it will be considered for dynamic search, in fact the same as the symbol of the dynamic library.

  • To maintain run-time health, add this to your class header:

     __attribute__((weak_import)) @interface MyUploadManager 

    When the dynamic linker is running, it replaces nil instead of the class symbol instead of the class symbol.

Now you can run this without linker or runtime errors:

 if ([MyUploadManager class]) { self.uploadButton.hidden = NO; } 

Note. Starting with Xcode 7, the -U linker options conflict with BitCode, so you won’t be able to use this method for future projects.

+4
source

You can use the NSClassFromString function:

 Class MyUploadManager = NSClassFromString(@"MyUploadManager"); if (MyUploadManager) { self.uploadButton.hidden = NO; } 

NSClassFromString returns nil if the class is not found.

+2
source

To make a weak class reference, it can be included in the structure. The compiler can be told to weak link all the characters in the framework using the Other Linker Flag build setting.

 -weak_framework <framework_name> 

This allows MyModule.framework to loosely communicate with Uploader.framework during its creation. If someone using MyModule.framework does not communicate with Uploader.framework, then in the example above the button will not be displayed.

Frames and loose coupling

0
source

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


All Articles