Question which comes with enormous amount of doubts.

Method Swizzling is the aptness that Objective-C Runtime gives to us, to switch the implementation of an actual selector at runtime.

Let’s take simple example that we need to observer operation NSUserDefaults. And by operation it means.

[[NSUserDefaults standardUserDefaults] setObject:@”iWSKey value” forKey:@”iWSKey”];

Phew !! that seemed easy let’s dive into more deeper.

Time to perform category which extend the NSUserDefaults. I am going to create function called iwsSetObject:forKey:

#import "NSUserDefaults+MyUserDefaults.h"

@implementation NSUserDefaults (MyUserDefaults)

-(void)iwsSetObject:(id)value forKey:(NSString *)name {

    [self setObject:value forKey:name];

    NSLog(@"iws setObject %@ for key %@",value,name);

And let’s see how can we use it.

#import "ViewController.h"
#import "NSUserDefaults+MyUserDefaults.h"

@interface ViewController ()

@implementation ViewController

- (void)viewDidLoad {
      NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];    
 [userDefaults iwsSetObject:@"A value" forKey:@"iWSKey"]; 

This is simple! We extended NSUserDefaults with a new method that calls the original iwsSetObject:forKey and also applied logs on that. So for all write operation we will use iwsSetObject:forKey.

Problem ?
We actually solved one problem without knowing of it. If we need to observe all “write operations” from the code we wrote, this will do the trick.

let’s assume that we imported some framework here, let’s say Firebase framework which is saving some properties using NSUserDefault(I don’t know if Firebase is really using NSUserDefaults but lets assume that for the example purpose only)

It’s clear that we have a problem. We can’t log Firebase calls to setObject:forKey.

What can we do here ? How ?
Stay tuned for the Part – 2

Leave a Reply

Your email address will not be published. Required fields are marked *

8 − six =