Masa
Masa

Reputation: 519

getting @encode result from instance instead of the type in objective-c

If you have a type:

@interface Foo: NSObject
@property (nonatomic, strong) NSString *s;
@property (nonatomic) int i;
@end
...
Foo *instance = [[Foo alloc] init];

So, of course, you can get the type encoding:

@encode(Foo);  // {<class>=#<encoded ivars>}

But, what if you have the instance? Like:

@encode(instance);  // Obviously, not a valid call.

It doesn't seem all that hard to do it with the runtime: You can get the class from the instance, and name and the ivars from the class, and you can get the type encoding from the ivars. So, isn't there some way to do this? What am I missing?

Upvotes: 1

Views: 93

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90601

@encode() is a compile-time directive. @encode(instance) is invalid because @encode() operates on types. You could do @encode(typeof(instance)) but that would return "@" because instance is an object pointer type. You could also do @encode(typeof(*instance)) which will give you the encoding of the class that instance is declared to point to (which may differ from the class of object that it actually points to at runtime).

This distinction between declared and actual type is, of course, crucial. There's no way a compile-time directive can anticipate what the actual type will be at runtime.

It's also not clear, for any given use of @encode(), which type you would actually be interested in. If you want the runtime type, use the runtime functions to construct it yourself, as you suggest. If you want the static type, well, you have the type name right there in your code, so just put that into the @encode() directive. (You could use the typeof operator as I showed before, but that just introduces a layer of indirection that's not really helpful. You'll get the same type as is used in the declaration of instance.)

I should say, there are very few good reasons to use @encode(). You're probably a lot better of rethinking your use of it, anyway.

Upvotes: 3

Related Questions