How could I check for a particular property at runtime, along with its return type? - objective-c

Since property named "age" would always have a selector named "age" as well, I could use respondsToSelector as this question suggests and that will tell me if a particular selector exists at runtime in any given object.
If a property named "age" exists, I can verify that. How could I know if that selector (the read method for that property) returns an object (id) or non-object (int)?
Is such type determination possible at runtime, or is the Objective-C way to always assume that someone implemented that method using the type I'm hoping it used, or can I also verify the return type?
This is using the latest Objective-C version (LLVM 4.1) in XCode 4.5.
Update: This is the utility-category-on-NSObject that I came up with:
- (NSString*) propertyType: (NSString*)propname
{
objc_property_t aproperty = class_getProperty([self class], [propname cStringUsingEncoding:NSASCIIStringEncoding] ); // how to get a specific one by name.
if (aproperty)
{
char * property_type_attribute = property_copyAttributeValue(aproperty, "T");
NSString *result = [NSString stringWithUTF8String:property_type_attribute];
free(property_type_attribute);
return result;
}
else
return nil;
}
While looking into this question I also wrote this handy-dandy utility method that
can list all the properties on this object:
- (NSArray*) properties;
{
NSMutableArray *results = [NSMutableArray array];
#autoreleasepool {
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList([self class], &outCount);
for (i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char * aname=property_getName(property);
[results addObject:[NSString stringWithUTF8String:aname]];
//const char * attr= property_getAttributes(property);
//[results addObject:[NSString stringWithUTF8String:attr]];
}
if (properties) {
free(properties);
}
} // end of autorelease pool.
return results;
}

You could use class_copyPropertyList to get a list of properties declared in a class.
class_copyPropertyList
Describes the properties declared by a class.
And then property_getAttributes:
property_getAttributes
Returns the attribute string of an property.
Here you can find some more concrete hints and examples.
As a side note, the following statement:
Since property named "age" would always have a selector named "age" as well
is not correct, since a property can have custom getter and/or setter:
#property (nonatomic, getter=isImmediate) BOOL immediate;
EDIT:
Some sample code I found in another S.O. post:
const char * type = property_getAttributes(class_getProperty([self class], "myPropertyName"));
NSString * typeString = [NSString stringWithUTF8String:type];
NSArray * attributes = [typeString components separatedByString:#","];
NSString * typeAttribute = [attributes objectAtIndex:0];
NSString * propertyType = [typeAttribute substringFromIndex:1];
const char * rawPropertyType = [propertyType UTF8String];
if (strcmp(rawPropertyType, #encode(float)) == 0) {
//it's a float
} else if (strcmp(rawPropertyType, #encode(int)) == 0) {
//it's an int
} else if (strcmp(rawPropertyType, #encode(id)) == 0) {
//it's some sort of object
} else ....

One approach you can take, assuming you know the property name already, is to use the class_getProperty function. You can also use the property_copyAttributeValue() function to get just a particular attribute by name:
objc_property_t number_property = class_getProperty([MyClass class], "number");
char *number_property_type_attribute = property_copyAttributeValue(number_property, "T");
NSLog(#"number property type attribute = %s", number_property_type_attribute);
Will log:
2013-01-14 14:45:37.382 RuntimeFun[61304:c07] number property type
attribute = i
Assuming MyClass looks something like:
#interface MyClass : NSObject
#property (nonatomic) int number;
#end
#implementation MyClass
#end
One you have your type attribute string, you can then compare it to the various Objective-C type encodings. Once you're done with your comparison, be sure to call free() on your attribute string.

Related

Obj-c Xcode static analysis produces a "Dereference of null pointer" on pointer assignment

I am trying to implement a tricky thing: all my model classes have an automatic NSCoding implementation of their properties. This let me add and remove properties to my classes and do not worry about missing stuff being not encoded/decoded. (Actually, it serves also other purposes, but that's the main idea).
When initializing my object from archive with initWithCoder, thanks to the Obj-C runtime, I go through the list of my properties, and try to assign directly the ivars to the values. I do not want to go through setters for various and imperious reasons, hence setValue:forKey: is forbidden.
Interesting problem, isn't it? I must say I am not full confident with C-pointers subtleties...
Here is the code:
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList(class, &outCount);
for (unsigned int index = 0; index < outCount; index++) {
objc_property_t property = properties[index];
NSString *propertyNameString = [NSString stringWithUTF8String:property_getName(property)];
id value = [coder decodeObjectForKey:propertyNameString];
if (value == nil) {
continue;
}
const char *attributes = property_getAttributes(property);
NSString *typeAttribute = [[NSString stringWithUTF8String:attributes] substringWithRange:NSMakeRange(1, 1)];
const char *ivarName = [[#"_" stringByAppendingString:propertyNameString] UTF8String];
if ([typeAttribute isEqualToString:#"#"]) {
Ivar ivar = class_getInstanceVariable([self class], ivarName);
object_setIvar(self, ivar, value);
}
else if ([typeAttribute isEqualToString:#"d"]) {
double *doublePointer = getIvarPointer(self, ivarName);
*doublePointer = [value doubleValue];
}
else if ([typeAttribute isEqualToString:#"i"]) {
int *intPointer = getIvarPointer(self, ivarName);
*intPointer = [value intValue];
}
else if ([typeAttribute isEqualToString:#"c"]) {
char *charPointer = getIvarPointer(self, ivarName);
*charPointer = [value boolValue];
}
else if ([typeAttribute isEqualToString:#"Q"]) {
NSUInteger *uintegerPointer = getIvarPointer(self, ivarName);
*uintegerPointer = [value unsignedIntegerValue];
}
}
free(properties);
The 'getIvar' function looks like this (yes, I use class_getInstanceVariable on object class, since object_getInstanceVariable is not allowed with ARC...):
static void* getIvarPointer(id object, char const *name)
{
Ivar ivar = class_getInstanceVariable(object_getClass(object), name);
if (!ivar) return 0;
return (unsigned char *)(__bridge void *)object + ivar_getOffset(ivar);
}
When running Xcode's static analyzer, I get a warning saying "Dereference of null pointer (loaded from variable 'doublePointer')". Interestingly enough, a similar message appeared for int and NSUInteger, but seems to have disappear right now... It never appeared for 'char'.
Any idea, suggestion or insightful criticism would be very much appreciated.
I must say that, the code actually works. I do get automatic decoding of double and int in my object classes. But I want to understand why the static analyzer tells me such thing.
As your getIvarPointer() function can legibly return 0, you must handle this eventuality in each *ptr affectation I think.
For example:
if ([typeAttribute isEqualToString:#"d"]) {
double *doublePointer = getIvarPointer(self, ivarName);
if (doublePointer) {
*doublePointer = [value doubleValue];
} else {
// Handle this as you can ;)
}
}

How to resolve property getter/setter method selector using runtime reflection in Objective-C? (or reverse)

Objective-C offers runtime reflections feature. I'm trying to find getter/setter selector name of a declared property. I know the basic rule like field/setField:. Anyway I think runtime reflection should offer a feature to resolve the name for complete abstraction, but I couldn't find the function.
How can I resolve the getter/setter method selector (not implementation) of a declared property with runtime reflection in Objective-C (actually Apple's Cocoa)
Or reverse query. (method selector → declared property)
I think you can get the selector names only if the property is declared with explicit (setter = XXX and/or getter = XXX)
So to get the getter and setter selector names for some property 'furType' of the class 'Cat':
objc_property_t prop = class_getProperty([Cat class], "furType");
char *setterName = property_copyAttributeValue(prop, "S");
if (setterName == NULL) { /*Assume standard setter*/ }
char *getterName = property_copyAttributeValue(prop, "G");
if (getterName == NULL) { /*Assume standard getter */ }
I don't know of a reverse query, other than iterating through all the properties and looking for matches. Hope that helps.
A little update from my NSObject category. Hope this'll help some one:
+(SEL)getterForPropertyWithName:(NSString*)name {
const char* propertyName = [name cStringUsingEncoding:NSASCIIStringEncoding];
objc_property_t prop = class_getProperty(self, propertyName);
const char *selectorName = property_copyAttributeValue(prop, "G");
if (selectorName == NULL) {
selectorName = [name cStringUsingEncoding:NSASCIIStringEncoding];
}
NSString* selectorString = [NSString stringWithCString:selectorName encoding:NSASCIIStringEncoding];
return NSSelectorFromString(selectorString);
}
+(SEL)setterForPropertyWithName:(NSString*)name {
const char* propertyName = [name cStringUsingEncoding:NSASCIIStringEncoding];
objc_property_t prop = class_getProperty(self, propertyName);
char *selectorName = property_copyAttributeValue(prop, "S");
NSString* selectorString;
if (selectorName == NULL) {
char firstChar = (char)toupper(propertyName[0]);
NSString* capitalLetter = [NSString stringWithFormat:#"%c", firstChar];
NSString* reminder = [NSString stringWithCString: propertyName+1
encoding: NSASCIIStringEncoding];
selectorString = [#[#"set", capitalLetter, reminder, #":"] componentsJoinedByString:#""];
} else {
selectorString = [NSString stringWithCString:selectorName encoding:NSASCIIStringEncoding];
}
return NSSelectorFromString(selectorString);
}

Get property name as a string

I need a way to pass a property and get the name assigned to it. Any suggestions?
#property (nonatomic, retain) MyObject *crazyObject;
NSString *str = SOME_WAY_TO_GET_PROPERTY_NAME(crazyObject);
// Above method should return #"crazyObject"
You can try this:
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);
NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
NSLog(#"Names: %#", propertyNames);
It's as simple as this...expanding upon what Chuck already mentioned:
#ifndef STR_PROP
#define STR_PROP( prop ) NSStringFromSelector(#selector(prop))
#endif
You then use it like so:
NSString *strProp = STR_PROP(myProperty);
Background
Keep in mind that properties are really just, to quote Apple, "a syntactical shorthand for declaring a class’s accessor methods." In fact, by itself, the #property declaration doesn't even work. Your #synthesize statement translates the #property into the equivalent of two methods:
- (void)setCrazyObject:(MyObject *)something;
- (MyObject *)crazyObject;
Which one is used depends on the context surrounding your self.crazyObject. (#synthesize also creates a matching instance variable if you didn't do it yourself.) The offshoot of all this is that you can't really translate to and from a property with one single method.
Proposed Solution
You can use what Apple already provides:
NSString *foo = NSStringFromSelector(#selector(myClassProperty));
Or do something custom:
Given that self.crazyObject really translates to either [self crazyObject] or [self setCrazyObject:foo] by the time your code is running, ou'll probably need two methods, like:
- (NSString *)setterStringForProperty:(SEL)prop;
- (NSString *)getterStringForProperty:(SEL)prop;
You might then want at least 2 companion methods such as:
- (SEL)setterForPropertyName:(NSString *)propString;
- (SEL)getterForPropertyName:(NSString *)propString;
Within these methods, you can use the Foundation functions NSStringFromSelector and NSSelectorFromString to convert back and forth between SEL and NSString. Use whatever string manipulations you like to convert back and forth between your setter string (setCrazyObject) and your property name (crazyObject).
A complete solution is hard to provide without knowing the exact use case, but hopefully this provides some more clues for anyone trying to accomplish something similar. There might even be some useful things made possible by combining this approach with Oscar's answer.
Here is a function that returns the name of an ivar, so basically it not only returns the properties but any ivar of the class. I haven't found a way to get the property directly so I used the ivar trick.
#import <objc/objc.h>
/// -----
- (NSString *)nameOfIvar:(id)ivarPtr
{
NSString *name = nil;
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([self class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
id pointer = object_getIvar(self, ivar);
if(pointer == ivarPtr)
{
name = [NSString stringWithUTF8String:ivar_getName(ivar)];
break;
}
}
free(ivars);
}
return name;
}
After searching and debugging i find solution for me...
Added #import <objc/runtime.h>
Methods object_getIvar(id obj, Ivar ivar) send bad access and app crashes. i modify some code and it worked great:
+(NSString*)stringWithProperty:(id)property withClass:(id)controller
{
NSString *name = nil;
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([controller class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
name = [NSString stringWithUTF8String:ivar_getName(ivar)];
if ([controller valueForKey:name] == property)
{
break;
}
}
free(ivars);
}
return name;
}
Modifying the solution, it works when your object is allocated already, otherwise it returns nil:-
NSString * NSStringFromProperty(NSObject* property, NSObject* class)
{
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([class class], &propertyCount);
NSString *name = nil;
for (unsigned int i = 0; i < propertyCount; ++i)
{
name = [NSString stringWithUTF8String:property_getName(properties[i])];
NSObject *object = [class valueForKey:name];
if (object != nil && object == property)
{
break;
}
else
{
name = nil;
}
}
free(properties);
return name;
}
You can use
NSString *str = NSStringFromSelector(#selector(crazyObject));
The good thing about this approach is that:
Xcode will autocomplete word crazyObject for you.
When later on you will change the property name from crazyObject to myCrazyObject, Xcode will add a warning saying "unrecognized selector!" -- pretty good for debugging.
I use this method so often, that I even created a function, which allows to write less letters:
NSString * __nonnull sfs(SEL __nonnull theSelector)
{
if (!theSelector)
{
abort();
}
return NSStringFromSelector(theSelector);
}
Now your final solution can look like this:
NSString *str = sfs(#selector(crazyObject));
From Get property name as string, without using the runtime reference library, just define:
#define propertyKeyPath(property) (#""#property)
#define propertyKeyPathLastComponent(property) [[(#""#property) componentsSeparatedByString:#"."] lastObject]
And then you can do something like this:
NSLog(#"%#", propertyKeyPathLastComponent(appleStore.storeLocation.street)); //result: street
You may check my approach at Gist to get the string for a property with autocompletion and compile-time check.
How to use:
Get the property name for a class:
#interface AnyClass : NSObject
#property (strong) NSData *data;
#end
// == My approach ==
// C string for a class
PropertyNameForClass(AnyClass, data); // ==> "data"
// NSString for a class
PropertyStringForClass(AnyClass, data); // ==> #"data"
// Bad approach (no autocompletion; no compile-time check):
NSString *propertyName = #"data";
Get the property name for a protocol:
#protocol AnyProtocol
#property (strong) NSDate *date;
#end
// C string for a protocol
PropertyNameForProtocol(AnyProtocol, date); // ==> "date"
// NSString for a protocol
PropertyStringForProtocol(AnyProtocol, date); // ==> #"date"
Unconventional, hacky, ugly, late, but... as strong-named as it gets and works like a charm:
#define SOME_WAY_TO_GET_PROPERTY_NAME(p) p == p ? [[[[[[[NSString alloc] initWithCString:#p encoding:NSUTF8StringEncoding] componentsSeparatedByString:#"."] lastObject] componentsSeparatedByString:#" "] lastObject] stringByReplacingOccurrencesOfString:#"]" withString:#""] : #""
Sample usage:
NSLog(SOME_WAY_TO_GET_PROPERTY_NAME(self.customer.surname)); // surname
NSLog(SOME_WAY_TO_GET_PROPERTY_NAME([[self customer] birthDate])); // birthDate
...

Anyway to get string from variable name?

Say I have my class
#interface Person : NSObject { NSString *name; }
I need to get the name of NSString's within my class
Person *person = [[Person alloc] init];
NSLog(#"Name of variable %s\n", _NameofVariable_(person->name));
Thanks for the answers, here's the solution I came up from the replies
//returns nil if property is not found
-(NSString *)propertyName:(id)property {
unsigned int numIvars = 0;
NSString *key=nil;
Ivar * ivars = class_copyIvarList([self class], &numIvars);
for(int i = 0; i < numIvars; i++) {
Ivar thisIvar = ivars[i];
if ((object_getIvar(self, thisIvar) == property)) {
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
break;
}
}
free(ivars);
return key;
}
As easy as
#define VariableName(arg) (#""#arg)
Then you do:
NSObject *obj;
NSString *str = VariableName(obj);
NSLog(#"STR %#", str);//obj
You can get the names of a class's instance variables with the Objective-C runtime API function class_copyIvarList. However, this is rather involved, rarely done and almost never the best way to accomplish something. If you have a more specific goal in mind than mere curiosity, it might be a good idea to ask about how to accomplish it in Objective-C.
Also, incidentally, person.name doesn't specify an instance variable in Objective-C — it's a property call. The instance variable would be person->name.
You might use preprocessor stringification and a bit of string twiddling:
NSUInteger lastIndexAfter(NSUInteger start, NSString *sub, NSString *str) {
NSRange found = [str rangeOfString:sub options:NSBackwardsSearch];
if(found.location != NSNotFound) {
NSUInteger newStart = NSMaxRange(found);
if(newStart > start)
return newStart;
}
return start;
}
NSString *lastMember(NSString *fullName) {
if(!fullName) return nil;
NSUInteger start = 0;
start = lastIndexAfter(start, #".", fullName);
start = lastIndexAfter(start, #"->", fullName);
return [fullName substringFromIndex: start];
}
#define NSStringify(v) (##v)
#define _NameofVariable_(v) lastMember(NSStringify(v))
If the person object is exposed as a property of the class, you can use objc_msgSend to get the value.
So, if you could access person using
[object person]
You could also do
objc_msgSend(object, "person")
For more details on message sending, including how to pass arguments to methods, see the Objective-C Runtime Programming Guide section on Messaging
The following works as a macro:
#define STRINGIZE(x) #x

How do I list all fields of an object in Objective-C?

If I have a class, how can I list all its instance variable names?
eg:
#interface MyClass : NSObject {
int myInt;
NSString* myString;
NSMutableArray* myArray;
}
I would like to get "myInt", "myString", and "myArray". Is there some way to perhaps get an array of names that I can iterate over?
I've tried searching the Objective-C documentation but couldn't find anything (and I'm not sure what this is called either).
As mentioned, you can use the Objective-C runtime API to retrieve the instance variable names:
unsigned int varCount;
Ivar *vars = class_copyIvarList([MyClass class], &varCount);
for (int i = 0; i < varCount; i++) {
Ivar var = vars[i];
const char* name = ivar_getName(var);
const char* typeEncoding = ivar_getTypeEncoding(var);
// do what you wish with the name and type here
}
free(vars);
#import <objc/runtime.h>
NSUInteger count;
Ivar *vars = class_copyIvarList([self class], &count);
for (NSUInteger i=0; i<count; i++) {
Ivar var = vars[i];
NSLog(#"%s %s", ivar_getName(var), ivar_getTypeEncoding(var));
}
free(vars);
Consider gen_bridge_metadata, which is intended for a completely different purpose, but can produce XML files from Objective-C header files.