Uroš Milivojević
Uroš Milivojević

Reputation: 203

Access property name (e.g. self.theProperty) in ObjC

I'm trying to read property name but I'm not shore how. Is it possible in ObjC to get string "theProperty" from self.theProperty?

I know how to read all properties (with "class_copyPropertyList") and their names (with "property_getName") but couldn't find a way to do something like:

NSString *text = [self.theProperty somehowReadThePropertyName]; 
// expected result is: text == @"theProperty"

Any ideas?

Upvotes: 0

Views: 598

Answers (2)

kubi
kubi

Reputation: 49354

Here's how you would get a string representation of the getter for your property:

NSString *selectorName = NSStringFromSelector(@selector(theProperty));

And since you've already used property_getName to return a C string, you can get an NSString like this:

NSString *propertyName = [NSString stringWithCString:property_getName(property)
                                            encoding:NSUTF8StringEncoding];

But, what are you trying to accomplish? There may be a far better way to do what you need to do.

Upvotes: 1

Abizern
Abizern

Reputation: 150595

A problem you have is that when you call self.theProperty, you are getting an object of whatever type that property is. That object isn't generally going to know that it is part of another object with a particular property name.

You'll need to get the property name from a higher level than just calling it.

Upvotes: 0

Related Questions