Search code examples
iosobjective-carraysnsarray

Obj C - Accessing custom class properties from and array of class objects


I have a custom object class with some properties lets say.

@property (nonatomic,retain) NSString *Name;
@property (nonatomic,retain) NSString *ImgURL;
@property (nonatomic,retain) NSArray  *Messages;

I then go through a loop and populate the data and add each instance to an array like this

for(NSDictionary *eachEntry in details)
{
    ClientData *client;
    client.Name = [eachEntry objectForKey:@"name" ];
    client.ImgURL = [eachEntry objectForKey:@"img"];
    client.Messages = [eachEntry objectForKey:@"message" ];

    [_Data addObject:client];  
}

now in a table i want to display some of this data in a list, how can i get access to each property by name not key or index.

so at the moment i have this in my cellForRowAtIndexPath

 NSString *name = [[self.Data objectAtIndex:indexPath.row]  objectForKey:@"name"];

obviously this doesn't work because i haven't set keys

and i don't want to do this

NSString *name = [[self.Data objectAtIndex:indexPath.row]  objectAtIndex:1];

How can i access Client.Name etc


Solution

  • self.Data is an array of ClientData objects so you can just do:

    NSString *Name = ((ClientData *)[self.Data objectAtIndex:indexPath.row]).Name;
    

    or:

    ClientData *clientData = self.Data[indexPath.row];
    NSString *name = clientData.Name;