Objective-C Posing

Objective-C allows a class to wholly replace another class within the program. The replacing classing is said to "pose as" the target class. The NSObject contains the poseAsClass: method that enables you to replace the existing class.

Note - For the version, that supported posing, all the message sent to the target class are instead received by the posing class

Important - Posing was declared deprecated in Mac OS X 10.5 and it is not available for use thereafter. So for those people who aren't concerned about these deprecated methods can skip this chapter.

Objective-C Posing Example

Here is an example program, demonstrates the concept of posing in Objective-C:

/* Objective-C Posing - Example Program */
#import <Foundation/Foundation.h>

@interface my_string : NSString

@implementation my_string
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target_string
withString:(NSString *)replacement_string
	NSLog(@"The Target string = %@", target_string);
	NSLog(@"The Replacement string = %@", replacement_string);

int main()
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	[my_string poseAsClass:[NSString class]];
	NSString *string = @"Test";
	[string stringByReplacingOccurrencesOfString:@"a" withString:@"c"];
	[pool drain];
	return 0;

Now when we compile and run the above Objective-C program in older version of Mac OS X (V_10.5 or earlier), then we will get the following output:

2015-10-03 21:23:46.829 Posing[372:303] The Target string = a
2015-10-03 21:23:46.830 Posing[372:303] The Replacement string = c

As you can see from the above output, we have just polluted the original method with output implementation and this will get affected throughout all the NSString operations with the above method

Objective-C Online Test

« Previous Tutorial Next Tutorial »