我写了以下代码:
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *reportDic = [jsonparser objectWithString:json_string error:nil];
NSDictionary *reporttable = [reportDic objectForKey:@"reporttable"];
NSArray *rows = [reporttable objectForKey:@"rows"];
NSString *table = [[NSString alloc]initWithString:@"<table>"] ;
for (NSDictionary *row in rows)
{
table = [table stringByAppendingString:@"<tr>"];
NSArray *cells = [row objectForKey:@"cells"];
for (NSString *cell in cells){
table = [table stringByAppendingString:@"<td>"];
table = [table stringByAppendingString:cell];
table = [table stringByAppendingString:@"</td>"];
}
table = [table stringByAppendingString:@"</tr>"];
index++;
}
table = [table stringByAppendingString:@"</table>"];
return [table autorelease];
这些行是由jsonlib解析的json响应 这个字符串被返回到一个viewcontroller,将它加载到webview中,但是在完成调用它的方法后,我继续为这段代码获取exc_bad_access,我甚至不必将它加载到webview只是调用这个方法而不是使用nsstring导致调用方法完成时的错误...任何帮助将得到感谢。
- (void)viewDidLoad {
[super viewDidLoad];
AMAppDelegate *appDelegate = (AMAppDelegate*)[[UIApplication sharedApplication] delegate];
NSString * data = [appDelegate fetchTable:name psw:psw];
[webView loadHTMLString:@"this is html" baseURL:nil];
[data release];
}
有或没有释放,无关紧要
答案 0 :(得分:4)
您的内存管理错误。
变化:
NSString *table = [[NSString alloc]initWithString:@"<table>"] ;
为:
NSString *table = [[[NSString alloc]initWithString:@"<table>"] autorelease];
然后改变:
return [table autorelease];
为:
return table;
原因是你最后自动释放的表是前一行构建的表:
table = [table stringByAppendingString:@"</table>"];
因此,您需要两次自动释放(stringByAppendingString:
返回一个自动释放的实例),而根本不释放原始表。
答案 1 :(得分:1)
如何使用NSMutableString构建表格?您当前的方法存在的一个问题是,您将不必要地充斥自动释放池。
NSMutableString *table = [NSMutableString string];
[table appendString:@"<table>"];
for (NSDictionary *row in rows)
{
[table appendString:@"<tr>"];
NSArray *cells = [row objectForKey:@"cells"];
for (NSString *cell in cells){
[table appendFormat:@"<td>%@</td>", cell];
[table appendString:@"</tr>"];
index++;
}
[table appendString:@"</table>"];
return table;
答案 2 :(得分:0)
关于更新,如果您正确合并了tewhas建议,-fetchTable:psw:
会返回自动释放的 NSString
,因此您不应该在调用方法中发布它:
NSString *data = [appDelegate fetchTable:name psw:psw]
// ...
[data release]; // don't do that, data is autoreleased
-fetchTable:psw:
应该像这样处理table
:
NSString *table = [NSString stringWithString:@"<table>"] ;
// ... leave the rest as it is
return table;
请注意,您也在泄漏json_string
,应该-release
或-autorelease
。