Objective-C Removing Inherited Methods from a Class

For a subclass, is there a way to remove / stop from superclasses?

(i.e. nsstring has the length of the method. I want to stop the "mystring" class from the length method).

+3
source share
6 answers

You can override the method to call doesNotRecognizeSelector::

- (NSUInteger)length
{
    [self doesNotRecognizeSelector:_cmd];
}

But if you need to do this, you may need to rethink if you really want to subclass in the first place. It might be better to use composition instead of inheritance if you want to “inherit” certain types of behavior / methods.

+10
source

length NSString; NSString length.

, , NSObject. length NSString .

+13

respondsToSelector:, NO doesNotRecognizeSelector:.

+3

- " ". , NSAssert (NO, @ " " ) .

", X, Y", X.

+2

?

+1

doesNotRecognizeSelector:. :

- (id)copy
{
    [self doesNotRecognizeSelector:_cmd];
}

However, there is a good chance that this is the wrong thing. The interface for the class is a contract; he indicates that an instance that is a view of this class (which includes instances of the subclass) will accept this message. When MyString is passed as NSString and does not accept the message length, it violates the contract and most likely will cause the program to crash, since no one will consider handling the NSInvalidArgumentException from the call lengthto NSString.

+1
source

Source: https://habr.com/ru/post/1769234/


All Articles