iOS:应用程序崩溃,可能是由于类的实例化

标签 ios web-services sigabrt

我正在尝试调试我遇到的崩溃...

我从网络服务器获取一些数据,所以我设置了三个类: child 子连接 子解析器

ChildConnection 联系 web 服务并获取数据并启动 ChildParser,然后解析 xml 并将其保存为 Child 对象...

我已经在一个项目中使用它,我没有使用 ChildConnection,而是在 AppDelegate 中设置了连接,而我当前项目中遇到的问题是与委托(delegate)有关(至少是这样)我想)...因为我收到错误: -[AppDelegate children]: 无法识别的选择器发送到实例 0x6b07e80

我相当确定错误是由以下原因引起的:(注意:我对此很陌生)

- (ChildParser *) initChildParser {

    self = [super init];

    if(self)
    {
        childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
        NSLog(@"Init");
    }
    return self;
}

ChildConnection.h:

@interface ChildConnection : NSObject
{
    NSMutableArray *children;
    NSMutableData *webData;
}

@property (nonatomic, retain) NSMutableArray *children;

-(void)connectionSetUp;

@end

ChildConnection.m:

#import "ChildConnection.h"
#import "ChildParser.h"

@implementation ChildConnection
@synthesize children;

- (void)connectionSetUp
{
    NSString *soapMsg = 
    [NSString stringWithFormat:

    Soap message left out due to sensitive data
     ]; 


    NSURL *url = [NSURL URLWithString:@"Private"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];

    // Calculate the length of the post
    NSString *postLength =  [NSString stringWithFormat:@"%d", [soapMsg length]];

    // Set the headers
    [req addValue:postLength forHTTPHeaderField:@"Content-Length"];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:@"PRIVATE" forHTTPHeaderField:@"SOAPAction"];

    // Set the HTTP method and body
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self];

    if(myConnection)
    {
        NSLog(@"Connection established");
        webData = [NSMutableData data];
    } else
    {
        NSLog(@"Connection failed");
    }     
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
    NSLog(@"didReceiveResponse");
    [webData setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //NSLog(@"didReceiveData");
    [webData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError: %@", [error localizedDescription]);
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Finished loading");

    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:webData];

    //Initialize the delegate.
    ChildParser *parser = [[ChildParser alloc] initXMLParser];

    //Set delegate
    [xmlParser setDelegate:parser];

    //Start parsing the XML file.
    BOOL success = [xmlParser parse];
    /*
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error Error Error!!!");
    */

    //NSLog(@"Count: %@", [ count]);
}

@end

ChildParser.h:

@class Child;
@class ChildConnection;

@interface ChildParser : NSObject <NSXMLParserDelegate>
{
NSMutableString *currentElementValue;

    Child *aChild;

    ChildConnection *childConnection;
}

- (ChildParser *) initChildParser;

@end

.m:

#import "ChildParser.h"
#import "Child.h"
#import "ChildConnection.h"

@implementation ChildParser

- (ChildParser *) initChildParser {

    self = [super init];

    if(self)
    {
        childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
        NSLog(@"Init");
    }
    return self;
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName 
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName 
attributes:(NSDictionary *)attributeDict 
{
    NSLog(@"didstart");

    if([elementName isEqualToString:@"GetKidsResult"])
    {
        // initialize the array
        if(!childConnection.children)
        {
        childConnection.children = [[NSMutableArray alloc] init];

        }

    }

    else if([elementName isEqualToString:@"a:KeyValueOfintKidf4KEWLbb"])
    {
        if(!aChild)
        {
            //Initialize the child.
            aChild = [[Child alloc] init];
        }
    }

    //NSLog(@"Processing Element: %@", elementName);
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { 

    NSLog(@"foundcharacters");
    /*
    if(!currentElementValue) 
    {
    currentElementValue = [[NSMutableString alloc] initWithString:string];
    }
    else
    {
    [currentElementValue appendString:string];
    }*/

}

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
        //NSLog(@"El name: %@", elementName);

    if([elementName isEqualToString:@"GetKidsResult"])
    {
        NSLog(@"end of xml");
    return;    
    }

    if([elementName isEqualToString:@"a:KeyValueOfintKidf4KEWLbb"])
    {
        //NSLog(@"Found end of child");

        //[childConnection.children addObject:aChild];

        //NSLog(@"added");

        //int i = [childConnection.children count];
        //NSLog(@"Count: %d", i);
    //aChild = nil;
    }

    else if([elementName isEqualToString:@"a:Key"])
    {
        //NSLog(@"Found key: %@", currentElementValue);
        //aChild.key = [currentElementValue intValue];
        //NSLog(@"key: %@", aChild.key);
    }

    else if([elementName isEqualToString:@"b:CPR"])
    {
        //NSLog(@"Found cpr");
        //aChild.cpr = [currentElementValue intValue];
    }

    else if([elementName isEqualToString:@"b:CheckedIn"])
    {
        //NSLog(@"Found checkedIn");
        //aChild.checkedIn = [currentElementValue boolValue];
    }

    else if([elementName isEqualToString:@"b:FirstName"])
    {
        //NSLog(@"Found firstname: %@", currentElementValue);
        //[aChild setValue:currentElementValue forKey:@"firstName"];
        //aChild.firstName = currentElementValue;

    }

    else if([elementName isEqualToString:@"b:Gender"])
    {
        //NSLog(@"found gender");
        //aChild.gender = currentElementValue;
    }

    else if([elementName isEqualToString:@"b:Id"])
    {
        //NSLog(@"found id");
        aChild.idChild = [currentElementValue intValue];

    }

    else if([elementName isEqualToString:@"b:IsOnTour"])
    {
        //NSLog(@"found isontour");
        //aChild.isOnTour = [currentElementValue boolValue];

    }

    else if([elementName isEqualToString:@"b:LastName"])
    {
        //NSLog(@"found lastname: %@", currentElementValue);
        //aChild.lastName = currentElementValue;
    }

    else if([elementName isEqualToString:@"b:GroupName"])
    {
        //NSLog(@"found groupname");
        //aChild.groupName = currentElementValue;
    }

    currentElementValue = nil;


}

- (void)parserDidEndDocument:(NSXMLParser *)parser 
{
    NSLog(@"didEndDocument");

    //NSLog(@"Number of objects: %d", [childConnection.children count]);

    [[NSNotificationCenter defaultCenter] postNotificationName:@"finishedParsing" object:nil];
}

@end

更新

好的,所以更进一步......我现在在我使用数据的类中得到一个 SIGABRT:

#import "AllView.h"
#import "CustomCellNoSubtitle.h"
#import "DTCustomColoredAccessory.h"
#import "Child.h"
#import "ChildConnection.h"

@implementation AllView

@synthesize allChildrenTable, childView, whichGroupLabel, charIndex;

-(void)receivedData
{
    NSLog(@"data update gotten");

    charIndex = [[NSMutableArray alloc] init];
    listOfNames = [[NSMutableArray alloc] init];

    for(int i=0; i<[childConnection.children count]-1; i++)
    {
        // get the person
        Child *aChild = [childConnection.children objectAtIndex:i];

        // get both first and last name and join them
        NSString *joinName = [NSString stringWithFormat:@"%@ %@", aChild.firstName, aChild.lastName];

        // save the full name to an array of all the names
        [listOfNames addObject:joinName];

        // get the first letter of the first name
        NSString *firstLetter = [aChild.firstName substringToIndex:1];

        NSLog(@"first letter: %@", firstLetter);

        // if the index doesn't contain the letter
        if(![charIndex containsObject:firstLetter])
        {
            // then add it to the index
            NSLog(@"adding: %@", firstLetter);
            [charIndex addObject:firstLetter];
        }

    }

    [allChildrenTable reloadData];
 }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Deselect the row, so it's clear when the user returns
    [allChildrenTable deselectRowAtIndexPath:indexPath animated:YES];

    if(self.childView == nil)
    {
        ChildView *cView = [[ChildView alloc] initWithNibName:@"ChildView" bundle:[NSBundle mainBundle]];

        self.childView  = cView;
    }

    [self.navigationController pushViewController:childView animated:YES];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    // set the number of sections in the table to match the number of first letters
    return [charIndex count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // set the section title to the matching letter
    return [charIndex objectAtIndex:section];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
    // get the letter in each section
    NSString *alphabet = [charIndex objectAtIndex:section];

    // get the names beginning with the letter
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];

    NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];

    return [names count];
}

// set up an index
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return charIndex;
}

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

    static NSString *CellIdentifier = @"Cell";

    CustomCellNoSubtitle *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        //cell = [[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
        //cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell = [[CustomCellNoSubtitle alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        //cell.frame = CGRectZero;
    }
    /*
    //---get the letter in the current section---
    NSString *alphabet = [charIndex objectAtIndex:[indexPath section]];
    //---get all states beginning with the letter---
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
    NSArray *names = [listOfNames filteredArrayUsingPredicate:predicate];
    if ([names count]>0) {
        //---extract the relevant state from the states object---
        NSString *cellValue = [names objectAtIndex:indexPath.row];
        cell.primaryLabel.text = cellValue;
    }

    cell.myImageView.image = [UIImage imageNamed:@"kidblank.png"];*/


    return cell;
}

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

    //childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];
    childConnection =[[ChildConnection alloc] init];

    [allChildrenTable reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Set up a connection to the server to fetch the list of children
    ChildConnection *childConnection = [[ChildConnection alloc] init];
    [childConnection connectionSetUp];

    // Set up a listener to receive notice when the parser is done
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData) name:@"finishedParsing" object:nil];

}

最佳答案

问题看起来很简单。

在您粘贴的第一个函数中,您将应用委托(delegate)分配给变量 childConnection。

childConnection = (ChildConnection *)[[UIApplication sharedApplication] delegate];

您确实想要将 ChildConnection 类的新实例分配给该属性。像这样:

childConnection = [[ChildConnection alloc] init];

我知道 Objective-C 错误有时很难理解,但您遇到的错误实际上非常清楚:

[AppDelegate children]: unrecognised selector

所以它提示你在应用程序委托(delegate)上调用方法/属性“ child ”。但是,如果您不再使用它,为什么还要在应用程序委托(delegate)上调用任何东西呢?当它实际上被定义为 ChildConnection 类的属性而不是应用程序委托(delegate)时,为什么要在其上调用一个名为“children”的方法?

回答:因为您认为是 ChildConnection 的对象实际上是应用委托(delegate)。

更新:看起来您需要在多个地方使用 ChildConnection。最简单的方法是创建一个共享实例。将此方法添加到您的 ChildConnection 类:

+ (ChildConnection *)sharedConnection
{
    static ChildConnection *sharedConnection = nil;
    if (sharedConnection == nil)
    {
        sharedConnection = [[self alloc] init];
    }
    return sharedConnection;
}

现在,在您的其他类(class)中,无论您在哪里使用 [[ChildConnection alloc] init],都请改用 [ChildConnection sharedInstance]

关于iOS:应用程序崩溃,可能是由于类的实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154103/

相关文章:

ios - 当配置文件过期时会发生什么?

ios - 由于应用商店中的 Info.plist 文件中缺少目的字符串而被拒绝 react native iOS 应用

c# - 我可以从 PowerShell 访问我的自定义 .NET 类吗?

mysql - Apigility (ZF2) mysql 数据库连接

ios - Swift 中的多色文本

ios - 为什么 UITableView 中的部分在不同设备上的顺序不同?

ios - 在 App Store Connect 上找不到编辑版本。尝试使用 '--use_live_version true'

c# - 为什么我的 ServiceStack 服务会抛出异常?

c++ - 在以下程序中使用 C++ 获取 SIGABRT

swift - 无法识别的选择器发送到实例 0x7f9d19e02870 ISSUE with UIButton