Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: Accessing Object field within an Object

I am currently new to developing in xcode and I am wondering how to access fields of an object that is inside another object (ie. Car object inside Vehicle Object).

for my cellForRowAtIndexPath method, I am trying to access a field within my Patient Class that sits inside my Admission class. I have an array [myList] that holds admission objects and within admission objects, I have patient objects.

Here is the code where I am having a problem, within my cellForRowAtIndexPath method:

static NSString *CellIdentifier = @"SimpleCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [[admList objectAtIndex:row]admPatName];
    return cell;
}

Problem is on this line below:

cell.textLabel.text = [[myList objectAtIndex:row]??];

on the ?? area, I couldn't figure out the right reference to the field.

Any suggestions?

Thanks JR

like image 902
user1203227 Avatar asked Apr 08 '26 04:04

user1203227


1 Answers

Like this:

cell.textLabel.text = [[[myList objectAtIndex:row] patient] name];

Or, if you prefer, like this:

Admission *admission = [myList objectAtIndex:row];
cell.textLabel.text = admission.patient.name;

I'm guessing the problem you had was that dot syntax doesn't work directly on [myList objectAtIndex:row] because the compiler doesn't know what kind of object that is.

You can usually use dot or [...] syntax interchangeably in Objective-C, so if dot syntax doesn't work, try square brackets. For what it's worth, you could get it to work with dot syntax by casting the array object, but it's a bit messy with all the brackets:

cell.textLabel.text = ((Admission *)[myList objectAtIndex:row]).patient.name;
like image 158
Nick Lockwood Avatar answered Apr 10 '26 21:04

Nick Lockwood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!