Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use Objective-C Categories

When you implement a category of a class in a file, will all the instances of that class be of the category by default?

I'm new to Objective-C and I'm trying to make my uneditable UITextView non-selectable. I came across this answer using a category: https://stackoverflow.com/a/8013538/1533240

Which has the following solution:

@implementation UITextView (DisableCopyPaste)

-(BOOL) canBecomeFirstResponder
{
    return NO;
}
@end

I added the snippet to my code, but it doesn't seem to be working in that I can still select the text. My declaration of the UITextView is the usual:

titleLabel = [[UITextView alloc] initWithFrame:frame];

I tried changing the declaration to [DisableCopyPaste alloc] but that didn't seem to work.. haha.

Thanks!

like image 241
corgichu Avatar asked Apr 22 '13 18:04

corgichu


1 Answers

You misunderstand the point of categories. Categories add methods to an existing class. They must never be used to override existing methods. Doing so is undefined behavior (technically only undefined in one case, but you can't predict that case, so you must assume it applies).

If you need to override methods, you must subclass, not use categories. See the top answer to the question you linked.

like image 160
Rob Napier Avatar answered Oct 04 '22 12:10

Rob Napier