-1

I want to iterate over the properties of my models in Objective-C. I tried this. Created PropertyUtil class with method classPropsFor:(Class)klass. Please find the attachment. Used objc/runtime.h. The code which I got from the net. In my viewcontroller I am doing this. [PropertyUtil classPropsFor:[self.user class]];. self.user is User model class. What I want to know is how can i iterate over the properties of my models, let's username, password and those values.

User

PropertyUtilDescription Finally

Artem Novichkov
  • 2,356
  • 2
  • 24
  • 34
Kumar Utsav
  • 2,761
  • 4
  • 24
  • 38
  • Possibly duplicate of http://stackoverflow.com/questions/6615826/get-property-name-as-a-string – Artem Novichkov Dec 09 '16 at 14:18
  • 1
    Do not show pictures of code. – matt Dec 09 '16 at 15:20
  • A note about this code...the `getPropertyType` method has an error in that it returns a pointer to memory owned by an NSData object. After the return, under ARC, that memory will be freed so your result pointer is pointing to memory whose contents may change. I had a crash caused by this so I modified the code to use malloc for my result buffer. The caller to the `getPropertyType` function is responsible for freeing the returned pointer. – Michael Kurtz Dec 12 '18 at 18:54

1 Answers1

-1

You may want to manually list all properties your model has. Just add a method to your model:

+(NSArray*) propList {
    return @[@"prop1", @"prop2"];
}

Then just use key-value coding to get the value

[someObject valueForKey:@"prop1"];

That's pretty straight and simple way if you wish to avoid Obj-C meta functions. Since you add your properties manually anyway, you may also add them in your list as well.

That's of course, if you don't have a large amount of models already and you wish do them all at once.

krafter
  • 1,425
  • 1
  • 15
  • 28