Skip to content

Instantly share code, notes, and snippets.

@rustle
Last active December 14, 2015 02:59
Show Gist options
  • Save rustle/5017569 to your computer and use it in GitHub Desktop.
Save rustle/5017569 to your computer and use it in GitHub Desktop.
Example of an NSValue subclass with a return value on getValue:
#import <Foundation/Foundation.h>
@interface RSTLValue : NSValue
- (BOOL)getValue:(void *)value expectedSize:(size_t)expectedSize;
@end
struct Foo {
NSUInteger i;
char * bar;
};
int main(int argc, const char * argv[])
{
@autoreleasepool {
struct Foo foo;
foo.i = 1;
foo.bar = "string";
RSTLValue *value = [[RSTLValue alloc] initWithBytes:&foo objCType:@encode(struct Foo)];
struct Foo foo2;
if ([value getValue:&foo2 expectedSize:sizeof(struct Foo)])
{
NSLog(@"%li %s\n", foo2.i, foo2.bar);
}
else
{
NSLog(@"Fail");
}
value = [[RSTLValue alloc] init];
struct Foo foo3;
if ([value getValue:&foo3 expectedSize:sizeof(struct Foo)])
{
NSLog(@"%li %s\n", foo3.i, foo3.bar);
}
else
{
NSLog(@"Fail");
}
}
return 0;
}
@implementation RSTLValue
{
NSValue *_realValue;
size_t _expectedSize;
}
- (instancetype)init
{
self = [super init];
if (self)
{
_expectedSize = 0;
}
return self;
}
- (id)initWithBytes:(const void *)value objCType:(const char *)type
{
self = [self init];
if (self)
{
_realValue = [[NSValue alloc] initWithBytes:value objCType:type];
NSUInteger size;
NSUInteger align;
//const char * retval =
NSGetSizeAndAlignment(type, &size, &align);
_expectedSize = size;
}
return self;
}
- (BOOL)getValue:(void *)value expectedSize:(size_t)expectedSize
{
if (_realValue == nil)
{
return NO;
}
if (_expectedSize != expectedSize)
{
return NO;
}
[_realValue getValue:value];
return YES;
}
- (void)getValue:(void *)value
{
@throw [NSException exceptionWithName:@"" reason:@"" userInfo:nil];
}
- (id)forwardingTargetForSelector:(SEL)aSelector
{
return _realValue;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment