单元格未添加到TableViewController

时间:2011-03-30 06:36:57

标签: iphone objective-c core-data

当我点击我的uialertview上的添加按钮时,我的应用程序崩溃(冻结),它应该向表中添加一个单元格。该错误与我在此处发布的代码行有关:

以下是错误消息:

此行的SIGABRT:cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row]; 好吧我发现问题是因为eventArray持有一个对象而不是我需要的字符串。如何修改代码以使save / fetch正常工作?

应该发生的是当用户将一个字符串输入到警报视图并按下ok时,它应该保存到例程实体的name属性中,并且表视图应该相应地更新自己。

这是我的viewController代码:

#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#import "Routine.h"
#import "CurlAppDelegate.h"

@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize managedObjectContext;

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)addEvent
{
    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

    NSManagedObject *newRoutineEntry;
    newRoutineEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:context];

    NSError *error = nil;
    if (![context save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    CurlAppDelegate *curlAppDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = [curlAppDelegate managedObjectContext];

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:context];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        NSString *entered = [(AlertPrompt *)alertView enteredText];
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        }
    }
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellEditingStyleDelete reuseIdentifier:CellIdentifier] autorelease];
    cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];

    return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

这是控制台输出:

2011-03-30 02:31:44.725 Curl[3303:707] -[Routine isEqualToString:]: unrecognized selector sent to instance 0x19d650
2011-03-30 02:31:44.824 Curl[3303:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Routine isEqualToString:]: unrecognized selector sent to instance 0x19d650'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x3234564f __exceptionPreprocess + 114
    1   libobjc.A.dylib                     0x36588c5d objc_exception_throw + 24
    2   CoreFoundation                      0x323491bf -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
    3   CoreFoundation                      0x32348649 ___forwarding___ + 508
    4   CoreFoundation                      0x322bf180 _CF_forwarding_prep_0 + 48
    5   UIKit                               0x354fcf65 -[UILabel setText:] + 32
    6   Curl                                0x0000682b -[RoutineTableViewController tableView:cellForRowAtIndexPath:] + 286
    7   UIKit                               0x355589ed -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 516
    8   UIKit                               0x3555876b -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 34
    9   UIKit                               0x3562a053 -[_UITableViewUpdateSupport(Private) _setupAnimationsForNewlyInsertedCells] + 3722
    10  UIKit                               0x35627b99 -[_UITableViewUpdateSupport initWithTableView:updateItems:oldRowData:newRowData:oldRowRange:newRowRange:context:] + 320
    11  UIKit                               0x35626dc1 -[UITableView(_UITableViewPrivate) _updateWithItems:withOldRowData:oldRowRange:newRowRange:context:] + 972
    12  UIKit                               0x35626473 -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 4750
    13  UIKit                               0x3562501d -[UITableView _updateRowsAtIndexPaths:updateAction:withRowAnimation:] + 204
    14  UIKit                               0x356302b9 -[UITableView insertRowsAtIndexPaths:withRowAnimation:] + 20
    15  Curl                                0x00005dc3 -[RoutineTableViewController addEvent] + 398
    16  Curl                                0x000064b1 -[RoutineTableViewController alertView:willDismissWithButtonIndex:] + 228
    17  UIKit                               0x35621ee1 -[UIAlertView dismissWithClickedButtonIndex:animated:] + 192
    18  UIKit                               0x35621d25 -[UIAlertView(Private) _buttonClicked:] + 280
    19  CoreFoundation                      0x322b5571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 24
    20  UIKit                               0x35513ec9 -[UIApplication sendAction:to:from:forEvent:] + 84
    21  UIKit                               0x35513e69 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
    22  UIKit                               0x35513e3b -[UIControl sendAction:to:forEvent:] + 38
    23  UIKit                               0x35513b8d -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 356
    24  UIKit                               0x35514423 -[UIControl touchesEnded:withEvent:] + 342
    25  UIKit                               0x35512bf5 -[UIWindow _sendTouchesForEvent:] + 368
    26  UIKit                               0x3551256f -[UIWindow sendEvent:] + 262
    27  UIKit                               0x354fb313 -[UIApplication sendEvent:] + 298
    28  UIKit                               0x354fac53 _UIApplicationHandleEvent + 5090
    29  GraphicsServices                    0x30557e77 PurpleEventCallback + 666
    30  CoreFoundation                      0x3231ca97 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
    31  CoreFoundation                      0x3231e83f __CFRunLoopDoSource1 + 166
    32  CoreFoundation                      0x3231f60d __CFRunLoopRun + 520
    33  CoreFoundation                      0x322afec3 CFRunLoopRunSpecific + 230
    34  CoreFoundation                      0x322afdcb CFRunLoopRunInMode + 58
    35  GraphicsServices                    0x3055741f GSEventRunModal + 114
    36  GraphicsServices                    0x305574cb GSEventRun + 62
    37  UIKit                               0x35525d69 -[UIApplication _run] + 404
    38  UIKit                               0x35523807 UIApplicationMain + 670
    39  Curl                                0x0000304f main + 82
    40  Curl                                0x00002ff8 start + 40
)
terminate called after throwing an instance of 'NSException'
(gdb) 

3 个答案:

答案 0 :(得分:0)

以上是代码中的问题

   cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];

因为

 [eventsArray insertObject:routine atIndex:0];

eventsArray保持Routine课程的对象不是NSString。 所以不要做

 cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];

<强>编辑:

Routine* myRoutine = [self.eventsArray objectAtIndex:indexPath.row];
//you need to get your stored text value from Routine class 
//let's say it myText
cell.textLabel.text = myText;

答案 1 :(得分:0)

我认为错误明确指出-[Routine isEqualToString:]:无法识别的选择器是问题所在。请检查一下。

答案 2 :(得分:0)

当应用程序崩溃时,使用debbuger查看[RoutineTableViewController tableView:cellForRowAtIndexPath:]方法。 如果你想这样做:

cell.textLabel.text = [self.eventsArray objectAtIndex:indexPath.row];

您必须确保将NSString对象放在eventsArray而不是Routine对象中。