Difference between method swizzling and category in Objective c

1.7k views Asked by At

I was just understanding the method swizzling done in obj c Method Swizzling and dangers of using method swizzling and couldn't help but draw a comparison between doing method swizzling and overwriting method implementation using categories. They both help override the functionality of the predefined framework methods. So is there any difference between the two or they can be used interchangeably?

2

There are 2 answers

1
Sergey Kalinichenko On BEST ANSWER

The main difference is that Objective C prevents you from invoking the original implementation from a category override. This is because Objective-C's super invocations start from the super-class, while categories override methods on the same class level.

Method swizzling, on the other hand, lets you keep a reference to the original implementation as well, so that you could call it from inside your implementation. For example, in the article at your first link the author writes this:

- (void) logged_viewDidAppear:(BOOL)animated {
    [self logged_viewDidAppear:animated];
    NSLog(@"logged view did appear for %@", [self class]);
}

The second line makes a call to logged_viewDidAppear: method, which looks like an unconditional call to itself that should cause infinite recursion. However, this is not what happens: after swizzling, this call gets transformed into a call to the original viewDidAppear: because of the way method swizzling works.

In contrast, overriding a method from a category does not give you access to the logic of the method that you are overriding. It lets you replace the logic, but it does not let you extend it.

0
kandelvijaya On
  extension UIViewController{
public func myViewDidLoad(){
    self.viewDidLoad()
    //but you need to call this method everywhere replacing
}

//you cant do this
public func viewDidLoad(){
    self.viewDidLoad()
    //my code
}
}

Categories or extension let you do these: Add computed properties and computed type properties

Define instance methods and type methods

Provide new initializers

Define subscripts

Define and use new nested types

Make an existing type conform to a protocol

(from Apple)

They don't let you extend original method of the same class that you are extending and if you try like the above code method signature conflict pops up.

You might want to check this website to get the concept diagrammatically. I really loved it.

http://matteogobbi.github.io/blog/2014/12/15/extending-methods-in-a-category-by-method-swizzling/

Make sure to check this awesome article for good implementation detail: http://nshipster.com/method-swizzling/