NSNumber : method to return pointer to represented value
NSNumber : method to return pointer to represented value
- Subject: NSNumber : method to return pointer to represented value
- From: "email@hidden" <email@hidden>
- Date: Fri, 21 Feb 2014 12:12:33 +0000
I require an pointer to the value represented by an NSNumber.
No interior pointer exists as the class is immutable.
My best attempt, a category that shadows the represented value, is as follows though I am wondering if I have missed a trick somewhere.
NSNumber uses tagged pointers and my unit tests indicate that the category works okay with tagged pointers such as @(1).
@Implementation NSNumber (Dubrovnik)
static const char valueShadowKey;
- (const void *)pointerToShadowValue
{
NSData *shadowData = [self valueShadowData];
if (!shadowData) {
// get the size of the encoded type
NSUInteger typeSize = 0;
NSGetSizeAndAlignment([self objCType], &typeSize, NULL);
// allocate data storage and copy value into it
NSMutableData *data = [NSMutableData dataWithLength:typeSize];
[self getValue:[data mutableBytes]];
shadowData = [NSData dataWithData:data];
// persist the data
[self setValueShadowData:shadowData];
}
// return interior pointer
return [shadowData bytes];
}
- (void)setValueShadowData:(NSData *)data
{
if ([self valueShadowData]) {
NSLog(@"Unexpected call to %@ - %@“, self, NSStringFromSelector(_cmd));
objc_setAssociatedObject(self, &valueShadowKey, nil, OBJC_ASSOCIATION_RETAIN);
}
objc_setAssociatedObject(self, &valueShadowKey, data, OBJC_ASSOCIATION_RETAIN);
}
- (NSData *)valueShadowData
{
NSMutableData *shadowData = objc_getAssociatedObject(self, &valueShadowKey);
return shadowData;
}
@end
Why do I need the pointer?
I am using NSNumber instances in collections as keys.
In order to index a Mono collection with the NSNumber instance I require to pass a pointer to the represented value to Mono.
All part of https://github.com/ThesaurusSoftware/Dubrovnik
Jonathan
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden