Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak Link My Own Objective-C Class

Tags:

objective-c

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.

like image 976
Onato Avatar asked May 29 '14 21:05

Onato


1 Answers

To weak link a class e.g. MyUploadManager in your own executable:

  1. 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.

  2. 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.

like image 168
Glen Low Avatar answered Oct 10 '22 01:10

Glen Low