开发者

How to check if a string is an object's instance variable or not?

I have one question about the variables of an object, I would like to know if I can check if a string is an object's instance variable or not? Below, an example to illustrate my issue :

I have an object - MyObject.h :

@interface MyObject :  NSObject  
{
    //Variables
    id myVariable1;
    id myVariable2;

}
@property (nonatomic, retain) id myVariable1;
@property (nonatomic, retain) id myVariable2;

And I have also an array list:

NSArray * myArray = [[NSArray alloc] initWithObjects:@"myVariable1",@"myVariable2",@"myVariable3",@"myVariable4",nil]; 

I would like to know if it's possible to determinate which strings in the array list aren开发者_JAVA百科't defined as variable in the object MyObject.

=> myVariable3 and myVariable4 for this case.

I tried to use "isKindOfClass", "isMemberOfClass", "valueForKeyPath", "valueForKey" but without success... Let me know if you have some advices to resolve my problem :)


Assuming the properties aren't using a custom setter name, you could do:

MyObject *object = ...;
for (NSString *name in myArray) {
  SEL getterName = NSSelectorFromString(name);
  if ([object respondsToSelector:getterName]) {
    NSLog(@"MyObject has a method named %@", getterName);
  } else {
    NSLog(@"MyObject does not have a method named %@", getterName);
  }
}


I would create an object to use for comparison using the NSClassFromString class.

if ([myClass isKindOfClass:NSClassFromString(myClassString)] {
   // class matches string
} else {
   // class doesn't match
}


It's easier to check if values in the array are properties of some object. As in your case the valueForKey: should have worked only if myInstance1 and myInstance2 are non-nil objects. You'd just need to implement - (id)valueForUndefinedKey: method to return nil and all would be fine and dandy.

You can also try using object_getInstanceVariable method while iterating through an array and fetching each possible instance variable separately. I believe that undeclared instances should return NULL pointer (as opposed to nil instances that are declared but undefined).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜