0

我有一个奇怪的错误,我似乎找不到任何文档或帖子。当我尝试使用标准教科书方法连接到我的 Web 服务(已更改 URL 以保护隐私)时,我在 [NSURLConnection initWithRequest] 上收到 EXC_BAD_INSTRUCTION 或 EXC_BAD_ACCESS。

最奇怪的是,有时我可以毫无例外地越过违规线,但 10 次中有 9 次会导致此错误。有什么建议么?

- (void)viewDidLoad {
    NSURL *url = [NSURL URLWithString:@"http://heres/where/my/webservice/url/is/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0];

    // cancel any old connection
    if(connection) {
        [connection cancel];
        [connection release];
    }

    // create new connection and begin loading data
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if(connection) {
        // if the connection was created correctly, release old data (if any), and alloc new
        [data release];
        data = [[NSMutableData data] retain];
    }

    [url release];
    [request release];
}

任何帮助或建议或 RTFM 将不胜感激!

4

2 回答 2

1

您正在释放自动释放的对象:

NSURL *url = [NSURL URLWithString:@"…"];
NSURLRequest *request = [NSURLRequest requestWithURL:url …];
// …
[url release];
[request release];

我认为 Clang 应该能够捕捉到这些,请参阅 Build → Build and Analyze (Cmd-Shift-A)。Clang 是你的朋友,习惯吧。

于 2009-11-20T06:15:58.610 回答
0

EXC_BAD_ACCESS 表示您正在尝试释放一个已经被释放的对象。正如 zoul 所说,您使用的 url 和 request 方法是自动释放方法,因此您不应该在代码末尾手动释放它们。

你应该做的是接受他的回答……因为他是对的。

于 2009-11-25T08:28:01.117 回答