I ran into a small problem. I created a UITableView where the user can add his contacts from his addressbook. The firstName gets displayed in the first row, the lastName in the second one. I know where the problem is, because right now I actually tell him how to do that.
But how can I tell him to display both names in the same cell? I did it with the following methods but they don’t work.
-(void)addObjectsFromArray:(NSArray *)otherArray
{
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObjectsFromArray:menuArray];
NSLog(@"%@", myArray);
[self.tableView reloadData];
}
The problem is that I cannot display objects from myArray because cellforRowAtIndex method does not get the value. And with that one I get the same result (firstName first Row, lastName second Row):
NSArray *objects = [[NSArray alloc] initWithObjects:firstName, lastName, nil];
NSString *cellValue = [objects objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
NSLog(@"%@", objects);
return cell;
Not only does your code display the first name and last name in different cells, it also does not work for rows at indexes greater than one. This is because your table data source reads from a brand-new array that you create with alloc/init on the first line, rather than reading from your model. Your little array contains only two objects, explaining the two rows.
Here is what you need to do: first, make an array of users available to your table’s data source. Suppose it’s called
userArray. Put user data for each user into that array. Suppose each user is stored as an object of typeMYUserthat responds to[user firstName]and[user lastName]calls with the first and the last name of the user.Now put this code into your table’s data source:
EDIT : If your
menuArraystores the first and the last names in separate consecutive string objects, you can still do it (though I recommend against it, because it will be confusing to people who maintain your program in the future).First, you need to change the method that returns the number of items in the table to return
menuArray.count / 2instead of justmenuArray.count. Then you can modify your code as follows:EDIT2 : Here is how you create a class that stores the first and the last name of a user. You add the
@interfacepart toMYUser.h, and the@implementationpart toMYUser.mfile. You then importMYUser.hin .m files from which you referenceMYUserclass, and useinitWithFirstName:andLastName:to initialize new instances. The sample below assumes that you use ARC:MYUser.h file:
MYUser.m file: