Search code examples
iosobjective-cblockcategories

Why do we needed category when we can use a subclass? and Why we needed blocks when we can use functions?


These two questions are quite common when we search it but yet I need to get a satisfying answer about both.When ever we search a difference between say subclass and a category we actually get definition of both not the difference.I went to an interview to a very good MNC working on iOS and I was encountered with these two questions and I gave almost all the answers I have read here but the interviewer was not satisfied.He stuck to his questions and was that-

  1. Why do we needed category when we can use a subclass?

  2. Why we needed blocks when we can use functions?

So please explain me what specific qualities blocks and category add in objective C that their counter part can't do.


Solution

    1. You can't use subclassing when someone else is creating the objects. For instance, NSString is returned from hundreds of system APIs, and you can't change them to return MyImprovedString.

    2. Functions split up the logic; blocks allow you to write it closer together. Like:

      [thing doSomethingAndWhenFinishedDo: ^{ some_other_thing; }];

    the same code written with functions would put the second part of the logic several lines away in the file. If you have a few nested scopes in your logic then blocks can really clean it up.