Objective C - problem with NSMutableArray and NSTableView

I have a class named Person and this class has a PersonName property (among others).

A MutableArray MyUserInfoArr

contains many Person objects.

I want to list every PersonName in a TableView cell? How should I do it? Thanks in advance.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    static NSString *CellIdentifier = @"Cell";
    Person *myPerson;    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
       cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    NSString *cellValue = [myUserInfoArr objectAtIndex:indexPath.row];
    cell.text = cellValue;

      


if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        Person *myPerson = [myUserInfoArr objectAtIndex:indexPath.row];
        cell.textLabel.text = myPerson.DisplayName;
        NSLog(@"abc %i",indexPath.section);
}

      

This is my code, it works, but it just returns the Person.DisplayName attribute of the last Person object in myUserInfoArr. How to fix it?

+2


source to share


2 answers


Person *person = [myUserInfoArr objectAtIndex:indexPath.row];
cell.textLabel.text = person.PersonName;

      



The reason your code is not working: the property text

should be NSString *

, not Person *

.

+1


source


The easiest way is to just set the text with

Person *person = [MyUserInfoArr objectAtIndex:[indexPath indexAtPosition:1]];
cell.textLabel.text = person.PersonName;

      

indexPath contains two indexes: first is the index of the section, the second is the index of the element in the section. So my guess is that in your case you have one section, so nothing to do with indexAtPosition: 0.



You also need to set up the table data source methods, they will tell your table how many sections / rows it should show:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [MyUserInfoArr count];
}

      

+2


source







All Articles