Is it possible to weak link my own objective-c classes?
I have seen that I can weak link a function or a 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.
To weak link a class e.g. MyUploadManager
in your own executable:
To keep the linker happy, add this 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 built into your executable. It will be considered for dynamic lookup instead, effectively the same as a dynamic library symbol.
To keep the runtime happy, add this to your class header:
__attribute__((weak_import)) @interface MyUploadManager
When the dynamic linker runs, it substitutes a nil
for the class symbol rather than crashing.
Now you can run this without either linker or runtime errors:
if ([MyUploadManager class]) {
self.uploadButton.hidden = NO;
}
Note: As of Xcode 7, the -U
linker options conflicts with BitCode, so you may not be able to use this technique for future projects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With