Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Categories

Tags:

objective-c

I've recently discovered categories and was wondering when it might be appropriate to use them in a user defined class/new class. For example, I can see the benefits of adding a category to an existing class like NSString, but when creating a new class what would be the advantage of adding a category to this rather than just implementing a normal method?

Hope this makes sense. Many thanks

Jules

like image 757
Jules Avatar asked Apr 13 '11 11:04

Jules


People also ask

What is the use of categories?

We use categories to organize our world and our thoughts. The aisles of a grocery store, the clothes in our closets, and the books in the library are all arranged and sorted based on categories. Our ability to understand and navigate these categories makes it easy to find what we're looking for more efficiently.

What's the difference between categories and tags?

So, what's the difference between tags and categories? While categories indicate the genre of your post, tags are more specific and indicate the specific topic your post seeks to cover. The best tags use a few words to describe what the post is about.

What is the role of categories in blog?

Blog categories organize your site and allow readers to find the information they want. They're high-level topics that make it easy for people to understand what your blog is about and navigate to the content that interests them. Think of it like a table of contents.


2 Answers

The answer isn't really any different for your own classes than it is for framework classes. If you have multiple projects, you'll likely end up sharing some classes between them. However, you may want to extend some of your classes so that they work more easily with a specific project, but not want to include those extra methods in your other projects, where they might not make sense. You can use a category to extend your class without needing to subclass.

like image 190
Caleb Avatar answered Oct 13 '22 22:10

Caleb


If I understand your question correctly, creating a "new class" is always "subclassing" because you're subclassing NSObject at the very least.

You could use categories on a new class to separate out sections of responsibility of a complex class. For example, all the basic functionality (instance variables, accessors, description, etc.) can go in one file (the "main" class file) while all methods to support a protocol (such as NSTableViewDataSource) can go in another.

Some take this approach to keep things "neat". I'm a firm believer in "if it's my own custom class, all its code should be in one file" so I do not personally do this. I demarcate different logical aspects of the class' code with "#pragma mark Some Section Name" to help navigation and readability. Your mileage may vary.

like image 40
Joshua Nozzi Avatar answered Oct 13 '22 22:10

Joshua Nozzi