iPhone App崩溃 - viewDidLoad

时间:2011-07-13 22:55:37

标签: iphone objective-c xcode

当我向主viewcontroller中的viewDidLoad添加方法时,我的iphone应用程序崩溃了:

#import "dbQuestionGetterViewController.h"
#import "dbConnector.h";

@implementation dbQuestionGetterViewController
@synthesize questions;

-(void)viewDidLoad{
    //code to initialise view
    NSDictionary* arr = [dbConnector getQuestions:2 from:@"http://dev.speechlink.co.uk/David/get_questions.php"];
    questions = arr;
    [arr release];  
    [super viewDidLoad];
}

我从dbConnector类调用静态方法,但在加载之前它崩溃了..

dbConnector中的方法:

//method to 
+(NSDictionary*)getQuestions:(NSInteger)sectionId from: (NSString*) url{
    //connect to database given by url
    //NSError        *error = nil;
    //NSURLResponse  *response = nil;
    NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:@"section=%@", sectionId];
    NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPMethod: @"POST"];
    //post section 
    [request setHTTPBody: myRequestData];

    //store them in the dictionary
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *questions = [json objectFromJSONString];
    [json release];

    [request release];
    return [questions autorelease];
}

我做错了什么?

3 个答案:

答案 0 :(得分:1)

您正在发布arr返回的getQuestions对象。由于您已将此对象标记为autorelease,因此您无需自行明确释放它。从viewDidLoad中删除以下行,您应该设置:

[arr release];

此外,您的myRequestString是可疑的。你正在调用string类方法,它返回一个完全分配和初始化的字符串,但是你在它上面调用initWithFormat,这通常用于你只是alloc的字符串 - 编辑。将该行替换为:

[[NSMutableString alloc]initWithFormat:@"section=%@", sectionId]

然后在[request release]之后立即发布。

答案 1 :(得分:1)

从静态方法返回的NSDictionary是自动释放的。但是你在viewDidLoad方法中释放它。

答案 2 :(得分:1)

首先,你没有对这段代码做任何事情:

NSMutableString* myRequestString = [[NSMutableString string]initWithFormat:@"section=%@", sectionId];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url]]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPMethod: @"POST"];
//post section 
[request setHTTPBody: myRequestData];

删除它。

其次,questions已经自动释放。

NSDictionary *questions = [json objectFromJSONString]; // < autoreleased

所以简单地做return questions;应该有效。

这也意味着您应该在任何情况下释放此返回值。因此,摆脱这个:

[arr release];