copying an object instance using NSCopyMemoryPages
copying an object instance using NSCopyMemoryPages
- Subject: copying an object instance using NSCopyMemoryPages
- From: Matthew Johnson <email@hidden>
- Date: Fri, 21 Nov 2003 14:35:41 -0600
I would like to make a category on NSArray that allows occassional
changes to the array with no performance impact except when the change
is made. This would be very useful when changes to the array happen,
but are extremely rare. The idea is that it would use
forwardInvocation: to make a mutable copy, invoke the change, and then
get a static copy and replace the instance with the new static array.
I am including the code that I have so far at the end of this message.
What I am wondering is will this work and are there any caveats I
should look out for?
Thanks!
Matthew
Here is the code:
#import <objc/objc-class.h>
@implementation NSArray (PseudoMutableArray)
- (BOOL)respondsToSelector:(SEL)aSelector {
return [NSMutableArray instancesRespondToSelector:aSelector];
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
return [NSMutableArray
instanceMethodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
if ([NSMutableArray instancesRespondToSelector:[invocation
selector]]) {
//make a mutable copy of the array, invoke the selector, and
then make a new
//array that is not mutable using the post invocation contents
of the mutable array
NSMutableArray *mutableSelf = [self mutableCopy];
[invocation invokeWithTarget:mutableSelf];
NSArray *newSelf = [NSArray arrayWithArray:mutableSelf];
[mutableSelf release];
//check to make sure the new array has the same class. if not
the copy won't work.
Class myClass = [self class];
Class newArrayClass = [newSelf class];
if (myClass != newArrayClass) {
[self doesNotRecognizeSelector:[invocation selector]];
} else {
//deallocate self and replace self with the new self by
copying the memory of new self
//after making the new copy we need to make sure the retain
count matches.
// retain count starts at 1 when the object is returned
from arrayWithArray
int retainCount = [self retainCount];
[self dealloc];
NSCopyMemoryPages(newSelf, self, myClass->instance_size);
int i;
for (i = 1; i < (retainCount); i++) {
[self retain];
}
}
}
else
[self doesNotRecognizeSelector:[invocation selector]];
}
@end
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.