0

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

1
  • 1
    instance names beggining with small letter. For example: NSString *name; Commented Dec 17, 2015 at 14:30

2 Answers 2

1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Or: NSString *name = [self.data[indexPath.row] Name];.
BTW - the cast is not needed in the 2nd code example.
1

Key Value Coding (KVC). Replace objectForKey with valueForKey.

5 Comments

Hi Wain, does this give the same as JDx's answer, is there any reason to do it like this rather than JDx's
This answer doesn't apply to the question being asked.
KVC is a different and generic way of accessing a value from an object for a specified key. All of the options presented are runtime checks with different ways of making the compiler happy with the request. They all have the same end result.
Does the properties actual name class as the key because i am not giving them any keys when i add the data to the array
Yes, the key is used to search for an accessor method to call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.