我在iPhone上使用ASIHTTPRequest来调用服务器,然后服务器发送包含JSON文件的响应。我让它在基本级别上工作,但当我将它添加到我的项目中并调用服务器时,我的应用程序开始崩溃与bad_access。
我从viewDidLoad这样调用:
requestModel = [[RequestModel alloc]init];
NSURL *url = [[NSURL URLWithString:@"myURL"]retain];
[requestModel eventsRequestFor:@"myUsername" password:@"myPassword" forURL:url];
这会调用另一个名为RequestModel的类中的函数,我会尝试解压缩返回的数组(很多代码):
-(void)eventsRequestFor:(NSString*)username password:(NSString*)password forURL:(NSURL*)forURL {
//use ASIHTTPRequest to post to sever. Here you authenticate and recieve answer
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:forURL];
[request setUsername:username];
[request setPassword:password];
[request setDelegate:self];
[request setDidFailSelector:@selector(uploadFailed:)];
[request setDidFinishSelector:@selector(uploadFinished:)];
[request startAsynchronous];
[request release];
NSLog(@"Model called");
}
#pragma mark Model Delegates
- (void)uploadFinished:(ASIHTTPRequest *)request {
// Use when fetching text data
NSLog(@"upload start");
NSString *stringFromRequest = [[NSString alloc]init];
stringFromRequest = [request responseString];
[self buildArrayFromRequest:stringFromRequest];
//[stringFromRequest release];
}
- (void)uploadFailed:(ASIHTTPRequest *)request {
NSString *statusMessage = [request responseStatusMessage];
NSLog(@"%@",statusMessage);
NSError *error = [request error];
NSLog(@"%@",error);
}
-(void)buildArrayFromRequest:(NSString*)string {
NSArray *arrayFromData = [[NSArray alloc]init];
arrayFromData = [string yajl_JSON];
NSLog(@"This is the array from the JSON %@",[arrayFromData objectAtIndex:0]);
NSMutableArray *events = [[NSMutableArray alloc] init];
for(int i= 0; i < [arrayFromData count];i++)
{
/////code to unpack array
}
///here i try to populate table with unpacked array
FirstViewController *firstVC = [[FirstViewController alloc]init];
[firstVC createTableWithArray:events];
[firstVC release];
[arrayFromData release];
[events release];
}
关于我哪里出错的任何想法?好像我正在发布一个已经发布的对象,但我找不到它。
答案 0 :(得分:4)
编辑:你发布了一个不属于你的NSData。
您不需要这一行:
[arrayFromData release];
因为这个错误:
你已经把:
NSArray *arrayFromData = [[NSArray alloc]init];
arrayFromData = [string yajl_JSON];
当你需要的只是这个:
NSArray *arrayFromData = [string yajl_JSON]; // This doesn't need releasing
您正在发布已经自动释放的请求:(
// Create an autoreleased request object
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:forURL];
...
[request release]; // fail here - this line is not needed
仅供参考:
这是不需要的代码:
NSString *stringFromRequest = [[NSString alloc]init];
stringFromRequest = [request responseString];
您正在创建一个字符串对象,然后获得另一个。你正在制作的第一个将被泄露。此代码将执行您想要的操作:
NSString *stringFromRequest = [request responseString]; // This doesn't need releasing :)
但是,这是泄漏的原因,而不是您报告的崩溃。
(你的代码中的其他地方都有这种模式,而不仅仅是这里。)