refulgentis
refulgentis

Reputation: 2635

Way to get return type of a method in Objective-C?

I'm writing a generic 'attribute/key editor' view class on iOS, and it checks the type of the editing key using [objectForKey isKindOfClass:[NSDate class]], for example. I just ran into a wall when I realized that will fail if objectForKey is nil. Is there a way to get the class/return type for a generic Objective-C property, even if said property is nil? I know about method_getReturnType in the Objective-C run-time, but that sounds like overkill for what I need.

Upvotes: 3

Views: 2043

Answers (4)

Jens Ayton
Jens Ayton

Reputation: 14558

You can’t. Although return type information for methods is available, the return type encoding for methods which return objects is simply @, meaning “object reference”.

Upvotes: 3

Peter Hosey
Peter Hosey

Reputation: 96323

What you're asking for doesn't make sense.

Remember that a name alone does not identify a method. Objects respond to those messages (or not); a method does not exist alone, only as part of an object (or class).

Having no object, you cannot tell from it what hypothetically sending a message to an object would return.

ETA: How is it that you could be editing the attributes of something, but not have the object to edit in order to examine its properties? It seems like you have a bug somewhere else.

I know about method_getReturnType in the Objective-C run-time, but that sounds like overkill for what I need.

There are two ways. If you want to support informal properties (KVC-compliant accessor methods with no @property declaration), that's exactly what you need. If you only care about formal properties (@property), use the property_getAttributes function.

Upvotes: 2

M. Ryan
M. Ryan

Reputation: 7182

I don't know where your data is coming from, but you might want to consider supplanting nil with NSNull and that will allow you to gain NSObject-like properties on something that is technically null

But the null check becomes more pain in the ass.

It goes from object != nil to

(NSNull *)object != [NSNull null]

Upvotes: 0

mjdth
mjdth

Reputation: 6536

Can't you just first check to make sure that objectForKey != nil, and the continue with the isKindOfClass checking? If you make sure that the object doesn't equal nil first you can easily check or safely exit without any failures.

Upvotes: 0

Related Questions