Mario
Mario

Reputation: 23

Objective-C. access to property of item in array which consists of objects

I have the array which consists of objects:

ViewController *item1 = [ViewController new];
item1.name = @"Mary";
item1.Description = @"good girl";
ViewController *item2 = [ViewController new];
item2.name = @"Daniel";
item2.Description = @"bad boy";
ComplexArray= [NSArray arrayWithObjects: item1, item2, nil];`

i want to view in labels a name and description if name is equal Mary

for (int i = 0; i < [ComplexArray count]; i++) {
    if (item[i].name isEqualString:@"Mary") {
        _nameLabel.text= item[i].name;
        _DescriptionLabel.text= item[i].Description;
    }
}

Please help me

Upvotes: 0

Views: 364

Answers (2)

Natasha
Natasha

Reputation: 6893

Your problem is you didn't assign anything in item variable. Just update like this and it will work.

for (int i = 0; i < [ComplexArray count]; i++) {
    ViewController *item = [ComplexArray objectAtIndex:i]; // you missed this line.
    if ([item.name isEqualToString:@"Mary"]) { //you missed the opening "[" and closing "]"
        _nameLabel.text= item.name;
        _DescriptionLabel.text= item.Description;
    }
}

Upvotes: 0

Droppy
Droppy

Reputation: 9721

You basically had it. All I did was rename item to ComplexArray added [] around the isEqualToString call and added a break:

for (int i = 0; i < [ComplexArray count]; i++) {
    ViewController *item = ComplexArray[i];
    if ([item.name isEqualString:@"Mary"]) {
        _nameLabel.text= item.name;
        _DescriptionLabel.text= item.Description;
        break;    // Added
    }
}

There are other ways, but this approach is fine.

BTW: variables should start, by convention, with a lowercase character.

Upvotes: 1

Related Questions