Zaur Zaur - 5 months ago 8
Objective-C Question

Properties of objects on array (Objective-c)

I have a

NSObject
class which's name is
test.


class
test
has 3 property.
Name
,
age
,
id
;

I have 3 Objects in test class.
s
,
b
,
c
.

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?

Thanks...

Rob Rob
Answer

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;

@end

@implementation Person

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

    return person;
}

@end

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] (
    Rob,
    Rachel,
    Charlie
)

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

Person *person = people[1];
NSString *name = person.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 = person.name;
    NSInteger age = person.age;
    long long identifier = person.identifier;

    // now do whatever you want with name, age, and identifier
}