Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an array of properties for an object in Objective-C

Is it possible to get an array of all of an object's properties in Objective C? Basically, what I want to do is something like this:

- (void)save {
   NSArray *propertyArray = [self propertyNames];
   for (NSString *propertyName in propertyArray) {
      [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
   }
}

Is this possible? It seems like it should be, but I can't figure out what method my propertyNames up there should be.

like image 997
John Biesnecker Avatar asked Dec 17 '09 09:12

John Biesnecker


People also ask

How do you create an array of objects in Objective-C?

Creating an Array Object The NSArray class contains a class method named arrayWithObjects that can be called upon to create a new array object and initialize it with elements. For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil];

Can a property of an object be an array?

Just as object properties can store values of any primitive data type (as well as an array or another object), so too can arrays consist of strings, numbers, booleans, objects, or even other arrays.

How do you add properties to an array of objects?

We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value. according to the console log.


1 Answers

I did some more digging, and found what I wanted in the Objective-C Runtime Programming Guide. Here's how I've implemented the what I wanted to do in my original question, drawing heavily from Apple's sample code:

#import <Foundation/NSObjCRuntime.h>
#import <objc/runtime.h>

- (void)save {
    id currentClass = [self class];
    NSString *propertyName;
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        propertyName = [NSString stringWithCString:property_getName(property)];
        [self doSomethingCoolWithValue:[self valueForKey:propertyName]];
    }
}

I hope this will help someone else looking for a way to access the names of an object's properties programatically.

like image 136
John Biesnecker Avatar answered Oct 28 '22 08:10

John Biesnecker