开发者

Problem working with NSMutableArray to store objects other than just strings in UITableViewController

I am a novice using iPhone SDK and Objective C. I am facing a stupid issue with the NSMutableArray object.

I have a Team class and a Player class. Team class has an NSMutableArray object that holds the Player objects. Team class is initialized with initWithTitle:(NSString*)title constructor. Player has Name property.

Now, I have a simple Navigation based application with a UITableViewController that shows a row with Add Player. When this row is selected, it opens a UIViewController that has a textField in which user can enter new player name (ex.Player1). When clicked on back button, row with new player name should appear above the Add Player row. After adding the second player (eg.Player2), the rows should look like:

Player1

Player2

Add Player

I am using PlayerUpdatedDelegate with method

-(void)PlayerUpdated:(NSString*)playerName; to transfer new player name back to UITableViewController when back button is clicked. In this method I create a new Player object and add to Team using [team.players addObject:player];

The problem that I am facing is after entering player's name and clicking on back button, the application crashes when I am trying to access the player's name in - (UITableViewCell *)tableView:(UITableView *)tableView cellF开发者_JAVA技巧orRowAtIndexPath:(NSIndexPath *)indexPath method like below:

if (indexPath.row < [team.players count]) {
    Player *player = [team.players objectAtIndex:indexPath.row];
    [cell textLabel].text = [player name]; // This is the line that fails........
    [player autorelease];
}
else {
    [cell textLabel].text = @"Add New Player";
}

return cell;

Any help will be greatly appreciated. Thanks. If you want to take a look at the simple app, I have uploaded it to: http://www.box.net/shared/y4ct7carfr


You didn't use self with property, synthesize. When you write

title = teamTitle;

retain count of title will not increase and the program will also crash in Team class dealloc, because you release title whose retain count is 0. Correct tose errors like this

self.title = teamTitle;

Correct relevant codes first and retry. Edit

In -(void) setPlayerName:(NSString *)playerName try

self.name = playerName;


I found the solution. When I was retrieving the Player object from the NSMutableArray, I did not cast it to Player. When I cast it, it works. So that solves it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜