user564968
user564968

Reputation:

how do i add or replace methods of existing objective-c classes?

If I want to add one function in any class suppose Nsstring, or overwrite any method of that class how can I do this?

What is method or code for this?

Upvotes: 2

Views: 1592

Answers (2)

justin
justin

Reputation: 104698

if i want to add one function:

create a category:

@interface NSString (MONAdditions)
- (BOOL)mon_isDirectoryWritable;
@end
@implementation NSString (MONAdditions)
- (BOOL)mon_isDirectoryWritable { return random(); }
@end

(note: mon_ is used here as a prefix for the selector - a very good practice for your category methods)

or overwrite any method of that class how can i do this?

for obvious reasons, you shouldn't do this, especially for NSString. but...

you have a few options in objc/runtime.h. method_exchangeImplementations provides a simple approach:

#include <objc/runtime.h>

@interface MONSwap : NSObject

/*...*/

- (void)makeCoffee;
- (void)goToSleep;

@end

@implementation MONSwap

- (void)makeCoffee
{
    self.coffeeMachine.brew;
}

- (void)goToSleep
{
    self.electricity.disable;
}

@end

void LetsPlayAnEvilTrick() {
    Class swap = [MONSwap class];
    // see also class_getClassMethod
    Method a = class_getInstanceMethod(swap, @selector(makeCoffee));
    Method b = class_getInstanceMethod(swap, @selector(goToSleep));
    method_exchangeImplementations(a, b);
}

Upvotes: 5

Robin
Robin

Reputation: 10011

you are talking about subclassing in objective c check out the links

Is subclassing in Objective-C a bad practice?

Objective C subclass that overrides a method in the superclass

Upvotes: 0

Related Questions