Using runtime functions to match up object types safely when setting properties
Using runtime functions to match up object types safely when setting properties
- Subject: Using runtime functions to match up object types safely when setting properties
- From: Graham Cox <email@hidden>
- Date: Sat, 20 Dec 2008 11:53:26 +1100
In my app, I have an interface and code that allows the user to set up
different values that can be set as properties of an object. The user
is presented with a list of properties that can be set (suitably
converted for display in the UI) and then they can set up the values
of these properties, which can be one of five distinct types (a custom
type, an image, colour, string or numeric value).
I'd like to be able to gently prevent the user from making an
inappropriate choice. For example if the given property expects a
string, they should not be able to choose an image object.
Internally, I use KVC, specifically -setValue:forKey: to apply the
chosen object to the chosen property.
So I'm looking for a way to safely and reliably determine whether a
property will accept an object of a given type. I wrote this category
on NSObject as a simple wrapper on the runtime to attempt this, but it
doesn't work quite how I expected - any property that returns an
object simply returns '@' as its return type - I can't tell what class
it is. Can anyone point me in the right direction?
@implementation NSObject (RuntimeEnhancements)
- (NSString*) returnTypeOfPropertyNamed:(NSString*) aProperty
{
NSString* result = nil;
Method meth = class_getInstanceMethod([self class],
NSSelectorFromString(aProperty));
if( meth )
{
char* methType = method_copyReturnType( meth );
result = [NSString stringWithUTF8String:methType];
free( methType );
}
NSLog(@"object %@ (%p) return type: %@", self, self, result );
return result;
}
- (NSString*) typeOfArgumentAtIndex:(unsigned) indx forMethodNamed:
(NSString*) aMethodName
{
NSString* result = nil;
Method meth = class_getInstanceMethod([self class],
NSSelectorFromString(aMethodName));
if( meth )
{
char* argType = method_copyArgumentType( meth, indx );
result = [NSString stringWithUTF8String:argType];
free( argType );
}
NSLog(@"object %@ (%p) argument at index %d: %@", self, self, indx,
result );
return result;
}
- (BOOL) propertyNamed:(NSString*) aProperty returnsObjectOfClass:
(Class) cl
{
// tests whether the return type of the property named is the same as
the class <cl>
NSString* propType = [self returnTypeOfPropertyNamed:aProperty];
return [propType isEqualToString:NSStringFromClass(cl)];
}
@end
thanks, Graham
_______________________________________________
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