0

Is it possible to check and get the name of the class an object was initialized in?

Example: I have Class A. I created object ABObject using [[ABOBject alloc] init]; via an instance method.

How can I find out the class from which an instance ABObject was created, namely "A" here?

Mat
  • 202,337
  • 40
  • 393
  • 406
s6luwJ0A3I
  • 1,023
  • 1
  • 9
  • 22

1 Answers1

2

Objects can be created outside the context of a class, so it wouldn't make sense for this to be a built-in language feature.

If you do have to do this, one way to work around it would be to use the objc_setAssociatedObjects() function in objc/runtime.h immediately after any such object was instantiated. Something like:

ABObject *object = [[ABObject alloc] init];
objc_setAssociatedObject(object, @"InstantiatingClassKey", [self class], OBJC_ASSOCIATION_ASSIGN);

Then you could get it with objc_getAssociatedObject(object, @"InstantiatingClassKey").

I think you'd be better off re-assessing your design because this is not going to be particularly maintainable. Even extracting this into a category on NSObject to remove duplicated code you'll still have an extra step to remember and weird relationships between your objects.

Also, as Martin R. points out in the comments, I'm taking a shortcut and passing a string literal as the key argument for the function, in reality you'd want to follow the practice of using the address of some static or global variable.

Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
  • 2
    Minor remark: Your example relies on the fact that `@"InstantiatingClassKey"` is a compile time constant. I think the recommended pattern is `objc_setAssociatedObject(object, , ...)`. – Martin R Mar 17 '13 at 14:15
  • @MartinR you're absolutely correct, I took a shortcut for illustrative purposes. – Carl Veazey Mar 17 '13 at 14:21