模拟器没有到位

时间:2011-06-30 22:36:55

标签: ios uitableview core-data

我正在关注this tutorial以了解核心数据。我目前正在第4部分,添加事件。在第2节中,教程说在我被模拟器提示获取我的位置后,Add按钮将变为活动状态,但它永远不会变为活动状态,不知道可能发生了什么?

PS:如果我在获取位置之前将按钮硬编码为活动,则会出现以下错误:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSMutableArray objectAtIndex:]: index 0 beyond bounds for empty array'

在以下行中:

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                          withRowAnimation:UITableViewRowAnimationFade];

编辑:发布更多代码以获得更大的图片

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Locations";

    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addEvent)];
    addButton.enabled = NO;
    self.navigationItem.rightBarButtonItem = self.addButton;

    [[self locationManager] startUpdatingLocation];

    eventsArray = [[NSMutableArray alloc] init];

}

这是我遇到错误的方法:

-(void)addEvent{
    CLLocation *location = [locationManager location];

    if(location){
        return;
    }

    Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];

    CLLocationCoordinate2D coordinate = [location coordinate];
    event.latitude = [NSNumber numberWithFloat:coordinate.latitude];
    event.longitude = [NSNumber numberWithFloat:coordinate.longitude];
    event.creationDate = [NSDate date];

    NSError *error;
    if (![managedObjectContext save:&error]) {

    }

    [eventsArray insertObject:event 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];

}

我的appDidLaunch方法:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    RootViewController *rootViewController = [[RootViewController alloc] initWithStyle:UITableViewStylePlain];
    navigationController = [[UINavigationController alloc] init];

    NSManagedObjectContext *context = [self managedObjectContext];

    if(!context){

    }

    rootViewController.managedObjectContext = context;

    [self.navigationController pushViewController:rootViewController animated:NO];

    [rootViewController release];

    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];

    return YES;
}

2 个答案:

答案 0 :(得分:1)

您发布的代码中没有NSMutableArray。错误的问题在于您尝试访问空0中的对象(索引NSMutableArray)。找到那个数组,你可能会发现问题。

答案 1 :(得分:0)

您没有获得CLLocation对象。在addEvent方法的第三行中,你有if(location){ 返回 } 所以基本上每次成功从CLLocation * location = [locationManager location]获取位置对象;你只需返回而不执行方法的其余部分。