@property范围问题和内存问题

时间:2010-12-02 17:46:19

标签: iphone objective-c

我遇到了一个我不明白的崩溃。我从远程服务器下载了几个文件,当文件下载完毕后,我试图检索附加到请求对象的对象。

Tia寻求帮助!

S上。

主要类

for (TrainingEntry* _entry in objects) {

    HTTPRequest * request = [HTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", [[ConfigLoader config] objectForKey:@"Server"], _entry.url]]];
    [request setDownloadDestinationPath:[NSString stringWithFormat:@"%@/%@", documentsDirectoryPath, _entry.filename]];

    [request setEntry:_entry];
    [request setRaw:_entry.title];

    TrainingEntry * test = (TrainingEntry*)[request _entry];
    NSLog(@"title: %@", [test title]); //<= This works
    NSLog(@"filename: %@", [test filename]); //<= This works

    [[self networkQueue] addOperation:request];

}

// Start Queue
[[self networkQueue] go];

...
- (void)requestFinished:(HTTPRequest *)request {

    if ([[self networkQueue] requestsCount] == 0) {
        [self setNetworkQueue:nil]; 
    }

    NSLog(@"req: %@", [request raw]);
    NSLog(@"title: %@", [[request entry] title]); // <= This works
    NSLog(@"filename: %@", [[request entry] filename]); // <= This crashes

}

HTTPRequest对象

@interface HTTPRequest : ASIHTTPRequest {

}

@property (nonatomic, retain) TrainingEntry * entry; 
@property (nonatomic, retain) NSString * raw;

@end

TrainingEntry Class

@interface TrainingEntry : NSObject {
    NSString * title;   
    NSString * filename;
}

@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSString * filename;

2 个答案:

答案 0 :(得分:0)

可能给您带来麻烦的事情是您的财产声明中没有copy。您应该考虑对符合copy协议规范的所有对象使用NSCopying,尤其是NSString和其他集合类。

过去,retain属性的copy更改为NSString解决了类似的问题。

编辑:一些研究

This post可能有助于澄清为什么应该copy使用retain来表示不可变对象。

答案 1 :(得分:0)

发生崩溃时,会有回溯。

发布。

您的程序将在调试器中断,并且调用堆栈将在调试器UI中(或者您可以键入'bt

有了这个,崩溃的原因通常很明显。如果没有这个,我们就会批评代码。


如果崩溃:

NSLog(@"filename: %@", [[request entry] filename]); // <= This crashes

要么因为request过度释放而且不再可行,要么因为filename正在返回垃圾对象。鉴于request之前有效,filename可能已被过度释放。

您在哪里设置filename