开发者

cannot place methods in tableView: cellForRowAtIndexPath:

I have an开发者_JAVA技巧 NSMutableString named alphabets in my class. I put [alphabets characterAtIndex:i] or [alphabets length] in tableView: cellForRowAtIndexPath:. But when i use reloaddata the app crashes.

Edit: Should I do all the calculations with alphabets outside the tableView and then pass an array of values to tableView.

this is where "alphabets" appears

in @interface

NSMutableString *alphabets;

@implementation

- (IBAction) textFieldDoneEditing: (id)sender {

    Logic *myLogic = [[Logic alloc] init];
    alphabets = [NSMutableString stringWithCapacity:0];

    alphabets = [myLogic formatSentence: sentenceTextField.text];
    alphabets = [myLogic makeAscending: alphabets];

    [logicTable reloadData];

    // removes keyboard
    [sentenceTextField resignFirstResponder];
}

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

    static NSString *CellIdentifier = @"Cell";

    MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[MyTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // this causes all the problem  
    cell.textLabel.text = alphabets;

    return cell;
}


Just a guess without seeing any code, but is "alphabets" already garbage collected by the time cellForRowAtIndexPath is called...? Or do you have a retain hold on it already?

Show us some code snippets. One that creates/instantiates "alphabets" and one where it's used...

EDIT:

Based on the code snippets you've added in your question, it looks to me like you probably need:

[alphabets retain];

after your last assignment to "alphabets" -- I can't say for sure without seeing the implementation of "[myLogic makeAscending: alphabets]" -- if it calls a method that returns a temporary string, though, you'll need to retain it to keep it in a member variable (ivar).

Of course, since you need to retain it to access it throughout your own object's lifetime, you'll also have to release it appropriately in your implementation of dealloc.


The reason your app is crashing is probably because you are calling reloadData inside of cellForRowAtIndexPath. reloadData will cause cellForRowAtIndexPath to fire again, and you're stuck in an infinite loop until you run out of memory. Try setting a breakpoint in your cellForRowAtIndexPath, and watch it happen


I would do something like

if (alphabets) {
    cell.textLabel.text = alphabets;
}

because from your sample code it seems you might be assigning textLabel.text from an uninitialized pointer until someone edits textField.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜