开发者

Objective C - Problem with NSMutableArray and NSTableView

开发者 https://www.devze.com 2022-12-09 17:32 出处:网络
I have a clas开发者_运维技巧s named Person and in this class is the property PersonName (amongst others).

I have a clas开发者_运维技巧s named Person and in this class is the property PersonName (amongst others).

A MutableArray MyUserInfoArr contains many Person objects.

I want to list each PersonName in a Cell of a TableView? How do I do this? 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 ran, but it just return the attribute Person.DisplayName of the last object Person in the myUserInfoArr. How to fix it?


The easiest way would be 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 section index, the 2nd is the item's index within the section. So I'm assuming in your case you have a single section, that's why there is nothing to do with the indexAtPosition:0.

You also have to set up the table's data source methods, these tell your table view how many sections/rows it should show:

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


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

The reason your code doesn't work: the text property needs to be an NSString *, not a Person *.

0

精彩评论

暂无评论...
验证码 换一张
取 消