Question

Is it possible in IOS to dynamically load/create a function on a class at runtime?

I'm specifically thinking for example of adding a class the the app delegate at runtime, but I'm not sure it is even possible in the language?

For instance, this is used for push notifications, but could it be added dynamically by a Push framework behind the scenes at runtime?

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    ....
}

As an alternative, could it simply be defined in the framework, outside the app delegate file, but still a part of the app delegate logic?

Was it helpful?

Solution

Both are options.

Dynamically adding methods, is via a C function called class_addMethod. You can even change an existing method (and still use the original!), it's called method swizzling. You can read the Apple documentation, or google for other examples. Note that you will need something in the program to at least touch your library to get it loaded (if you put the swizzling in your class's +initialize method), and it's probably easiest overall to just have the user initialize your library with something along the lines of [MYLibrary applicationLaunchedWithDelegate:self launchOptions:launchOptions].

If you know the class you need to add the method to, you can use a category.

OTHER TIPS

you can put your self as app delegate and bypass all received delegates to old one for backward compatibility.here is a pseudo code.

1)by default we have this wiring:

ios -> appdelegate.m

now you need to put your self in the middle like :

ios -> framework -> appdelegate.m

2)so you can do it by set old delegate to another variable like: (in your framework delegate)

self.oldDelegate = [UIApplication sharedApplication].delegate;

and set yourself as application delegate:

[[UIApplication sharedApplication] setDelagate:self];

3)for backward compatibility you need to bypass all delegates to oldDeleagete

4)warning:this is pseudo code to give you the idea but remember you need to take care of multi threading of your app may be there is another framework like you and both are changing app delegates but will get wrong oldDelegate and your wiring will not work .so pay more attention to these kind of stuffs.look at this

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top