简体   繁体   English

iOS因EXC_BAD_ACCESS(代码= 1)崩溃

[英]iOS crashes with EXC_BAD_ACCESS(code=1)

I'm new to iOS, so don't be shy about pointing out any of my code that looks completely idiotic :) 我是iOS的新手,所以不要害羞指出我的任何看起来完全白痴的代码:)

Here goes... 开始...

Two view controllers - OrderViewController and LineItemViewController - when the user is on LineItemViewController, they can click a "Scan" button that sends a request to the server to mark this item as scanned. 两个视图控制器-OrderViewController和LineItemViewController-当用户使用LineItemViewController时,他们可以单击“扫描”按钮,该按钮向服务器发送请求以将该项目标记为已扫描。 That seems to work fine, but I get this error in the console app: 这似乎工作正常,但在控制台应用程序中出现此错误:

5/19/13 11:28:04.044 AM EvoScanner: tcp_connection_destination_fail net_helper_connect_fail failed 13/5/19上午11:28:04.044 EvoScanner:tcp_connection_destination_fail net_helper_connect_fail失败

The app still runs fine after getting that error. 收到该错误后,该应用仍然可以正常运行。 The issue is when I click "Back" to return to the OrderViewController, the app crashes with EXC_BAD_ACCESS(code=1). 问题是当我单击“上一步”返回到OrderViewController时,应用程序崩溃,并显示EXC_BAD_ACCESS(code = 1)。

I'm using XCode 4.6.2 with ARC enabled. 我正在使用启用了ARC的XCode 4.6.2。

Here's my LineItemViewController: 这是我的LineItemViewController:

// Interface
#import <UIKit/UIKit.h>
#import "LineItemModel.h"

@interface LineItemViewController : UIViewController
@property (strong, nonatomic) LineItemModel* _line_item;
-(void)setDetailItem:(LineItemModel *) lineItem;

@property (strong, nonatomic) IBOutlet UIButton *scanButton;
- (IBAction)scanItem:(id)sender;

@property (strong, nonatomic) IBOutlet UILabel *itemLabel;
-(IBAction)scanItem;
@end

// Implementation
#import "LineItemViewController.h"
#import "LineItemModel.h"
#import "HUD.h"
#import "JSONModelLib.h"

@interface LineItemViewController () {
  LineItemModel *_line_item;
}
@end

@implementation LineItemViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.itemLabel.text = _line_item.product_title;
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setDetailItem:(id)lineItem {
  if(_line_item != lineItem) {
    _line_item = lineItem;

    [self configureView];
  }
}

- (void)configureView
{
    // Update the user interface for the detail item.
    if (self._line_item) {
       // self.detailDescriptionLabel.text = [self.detailItem description];
    }
}

- (IBAction)scanItem:(id)sender {
    NSLog(@"Scanning!");
    NSString *string_url = [NSString stringWithFormat:(NSString *)@"%@/%@",  @"http://localhost:3000/api/scan_item", _line_item.id ];
    NSURL *url = [NSURL URLWithString:string_url];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSString *messageBody = [NSString stringWithFormat:@"status=%@",@1];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [messageBody length]];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
    [theRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [theRequest setHTTPBody:[messageBody dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if(theConnection)
    {
        NSLog(@"Connection Successful");

        //receivedData = [[NSMutableData data] retain];
    }
    else
    {
        NSLog(@"There was an error: ");
//        UIAlertView *alert1 = [[[UIAlertView alloc] initWithTitle:@"Alert" message:@"There was an issue sending the data. Please check your internet connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
//        [alert1 show];
    }
}
@end

And the OrderViewController: 和OrderViewController:

// Interface
#import <UIKit/UIKit.h>
#import "OrderModel.h"


@interface OrderViewController : UITableViewController
@property (strong, nonatomic) OrderModel* _order;
@property (strong, nonatomic) id detailItem;
@end

// Implementation
#import "OrderViewController.h"
#import "OrderModel.h"
#import "LineItemModel.h"
#import "LineItemCell.h"
#import "HUD.h"
#import "JSONModelLib.h"
#import "LineItemViewController.h"


@interface OrderViewController () {
    OrderModel* _order;
    NSMutableArray* listOfItems;
}
@end



@implementation OrderViewController

-(void)viewDidAppear:(BOOL)animated
{
    NSLog(@"View did appear");
    // show loader view
    //[HUD showUIBlockingIndicatorWithText:@"Fetching order"];

    //Initialize the array.
    listOfItems = [[NSMutableArray alloc] init];

    NSMutableArray *unPackedArray = [NSMutableArray array];
    NSMutableArray *packedArray = [NSMutableArray array];
    NSLog(@"ORDER: %@", _order);
    for(int i = 0; i < _order.line_items.count; i++) {
        NSLog(@"object in for loop: %@", _order.line_items[i]);
        LineItemModel *li = _order.line_items[i];
        if (li.qty_packed != li.quantity) {
            [unPackedArray addObject:(LineItemModel *)_order.line_items[i]];
        } else {
            [packedArray addObject:(LineItemModel *)_order.line_items[i]];
        }

    }
    NSLog(@"unpacked array: %@", unPackedArray);
    NSLog(@"packed array: %@", packedArray);

    NSDictionary *unPackedDict = [NSDictionary dictionaryWithObject:unPackedArray forKey:@"LineItems"];


    NSDictionary *packedDict = [NSDictionary dictionaryWithObject:packedArray forKey:@"LineItems"];

    [listOfItems addObject:unPackedDict];
    [listOfItems addObject:packedDict];


    // TODO: set the order id from the selected cell here
    [self.tableView reloadData];

    self.navigationItem.title = _order.customer_name;

}



- (void)setDetailItem:(id)newDetailItem
{
    NSLog(@"MAKE DETAIL ITEM");
    if (_order != newDetailItem) {
        _order = newDetailItem;

        // Update the view.
        [self configureView];
    }

    // show loader view
    [HUD showUIBlockingIndicatorWithText:@"Fetching order"];


    NSString *order_id = _order.id;
    NSString *url = [NSString stringWithFormat:(NSString *)@"%@/%@.%@",  @"http://localhost:3000/api/order", order_id, @"json" ];
    _order = [[OrderModel alloc] initFromURLWithString:url completion: ^(JSONModel *model, JSONModelError *err) {

        // hide loader view
        [HUD hideUIBlockingIndicator];

        [self.tableView reloadData];
    }];


}

- (void)configureView
{
    // Update the user interface for the detail item.

    if (_order) {
       // self.detailDescriptionLabel.text = [self.detailItem description];
    }
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    NSLog(@"View DID LOAD");
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#warning Potentially incomplete method implementation.
    // Return the number of sections.  One for Packed items, one for items not packed.
    return [listOfItems count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSDictionary *dictionary = [listOfItems objectAtIndex:section];
    NSArray *array = [dictionary objectForKey:@"LineItems"];
    return [array count];
}


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSLog(@"ORDER IN LINEITEM CELL: %@", _order);

    // NSLog(@"LINEITEM: %@", line_item);

    // New view code with subclass
    LineItemCell *cell = (LineItemCell *)[tableView dequeueReusableCellWithIdentifier:@"LineItemCell"];
    if (!cell) {
        cell = [[LineItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LineItemCell"];
    }

    // Get the Line Item object for this row and section
    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"LineItems"];
    LineItemModel* line_item = [array objectAtIndex:indexPath.row];


    cell.productLabel.text = line_item.product_title;
    cell.variantLabel.text = line_item.variant_title;

    int remaining = line_item.quantity - line_item.qty_packed;
    cell.remainingLabel.text = [NSString stringWithFormat:@"%i", remaining];
    // NSLog(@"LINE ITEM CELL: %@", cell);
    return cell;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    if(section == 0)
        return @"Unpacked Items";
    else
        return @"Packed Items";
}


/*
// 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;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"LineItems"];
    LineItemModel *li = [array objectAtIndex:indexPath.row];
    NSLog(@"Line Item in final: %@", li);


    LineItemViewController *vc = [segue destinationViewController];
    [vc setDetailItem:li];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */

}



@end

UPDATE: After setting breakpoints for all exceptions, the trace leads me to: 更新:为所有异常设置断点后,跟踪将我引导至:

#import <UIKit/UIKit.h>

#import "EvoAppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        // Breakpoint leads to this line
        // Thread 1: EXC_BAD_ACCESS(code=1, ...)
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([EvoAppDelegate class]));
    }
}

尝试取消链接IB中的delegatedatasource链接,并以编程方式在OrderViewController设置UITableViewdelegatedatasource

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM