gpt4 book ai didi

objective-c - NSString 、 EXC_BAD_ACCESS 和 stringByAppendingString

转载 作者:行者123 更新时间:2023-12-03 17:30:55 26 4
gpt4 key购买 nike

我写了以下代码:

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 响应该字符串返回到 View Controller ,将其加载到Web View 中,但是在调用它的方法完成后,我不断获得此代码的exc_bad_access,我什至不必将其加载到Web View 中,只需调用此方法而不是使用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];
}

无论有没有发布,都没有关系

最佳答案

你的内存管理是错误的。

更改:

NSString *table = [[NSString alloc]initWithString:@"<table>"] ;

至:

NSString *table = [[[NSString alloc]initWithString:@"<table>"] autorelease];

然后更改:

return [table autorelease];

至:

return table;

原因是您最后自动释放的表是由上一行构造的表:

table = [table stringByAppendingString:@"</table>"];

因此,您将自动释放两次(stringByAppendingString: 返回一个自动释放的实例),并且根本不释放原始表。

关于objective-c - NSString 、 EXC_BAD_ACCESS 和 stringByAppendingString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2909092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com