Zaur Zaur - 1 year ago 83
Objective-C Question

Properties of objects on array (Objective-c)

I have a

class which's name is

has 3 property.

I have 3 Objects in test class.

I am putting all of the objects to the array with:
NSArray *ary = [NSArray arrayWithObjects:@"a", @"b", @"c", nil];

I am trying to access to the data of property in that array. Which means I have to read, write the property of the object in array in the loop (for loop or while loop).

I found a lot of materials on the internet. The method that I was close to do was:

[[ary objectAtIndex:0] setName:@"example"];

This method was working with setters and getters. But it did give a horrible error. Is there any "WORKING" method to do it?


Rob Rob
Answer Source

Let's imagine a Person class:

@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic) NSInteger age;
@property (nonatomic) long long identifier;

+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier;


@implementation Person

+ (instancetype)personWithName:(NSString *)name age:(NSInteger)age identifier:(long long)identifier {
    Person *person = [[self alloc] init]; = name;
    person.age = age;
    person.identifier = identifier;

    return person;


You can then create an array of people like so:

NSArray *people = @[[Person personWithName:@"Rob" age:32 identifier:2452323],
                    [Person personWithName:@"Rachel" age:29 identifier:84583435],
                    [Person personWithName:@"Charlie" age:4 identifier:389433]];

You can then extract an array of people's names like so:

NSArray *names = [people valueForKey:@"name"];
NSLog(@"%@", names);

That will generate:

2013-09-27 14:57:13.791 MyApp[33198:a0b] (

If you want to extract information about the second Person, that would be:

Person *person = people[1];
NSString *name =;
NSInteger age = person.age;
long long identifier = person.identifier;

If you want to change the age of the third person, it would be:

Person *person = people[2];
person.age = 5;

Or, if you want to iterate through the array to extract the information, you can do that, too:

for (Person *person in people) {
    NSString *name =;
    NSInteger age = person.age;
    long long identifier = person.identifier;

    // now do whatever you want with name, age, and identifier
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download