Objective-C - 程序接收信号:“EXC_BAD_ACCESS”。 with(NSNumber floatValue)

时间:2010-12-13 05:27:23

标签: objective-c memory-management floating-point nsnumber

使用以下代码时,我得到Program received signal: “EXC_BAD_ACCESS”.

searchResultFileSize在我的界面中被声明为NSNumber。我不确定将它设置为什么属性。目前我将它作为:

@property (nonatomic, readonly) NSNumber *searchResultFileSize;

这是对的吗?我在以下几行中得到错误:

NSLog(@"float filesize: %f", [searchResultFileSize floatValue]); //Program received signal:  “EXC_BAD_ACCESS”.
HUD.progress = [resourceLength floatValue] / [searchResultFileSize floatValue]; //Program received signal:  “EXC_BAD_ACCESS”.

如果我注释掉第一行,它在第二行显然仍会失败。任何想法可能是什么问题?也许我的转换是错误的。以下是我使用这段代码的两种方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [responseData setLength:0];

    searchResultFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];

    NSLog(@"Float filesize: %f", searchResultFileSize);

    if ([searchResultFileSize intValue] != NSURLResponseUnknownLength) {
        HUD.mode = MBProgressHUDModeDeterminate;
        HUD.labelText = @"Getting Results";
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];

    NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[responseData length]];
    NSLog(@"resourceData length: %d", [resourceLength intValue]);
    NSLog(@"filesize: %d", searchResultFileSize);
    NSLog(@"float filesize: %f", [searchResultFileSize floatValue]); //Program received signal:  “EXC_BAD_ACCESS”.
    // HUD.progress is a float
    HUD.progress = [resourceLength floatValue] / [searchResultFileSize floatValue]; //Program received signal:  “EXC_BAD_ACCESS”.
    NSLog(@"progress: %f", [resourceLength floatValue] / [searchResultFileSize floatValue]);
}

1 个答案:

答案 0 :(得分:4)

你的问题在这里:

searchResultFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];

你需要retain来保持它,它是自动释放的。

searchResultFileSize = [[NSNumber numberWithLongLong:[response expectedContentLength]] retain];

我建议您将属性设置为(nonatomic, retain),然后您的代码中不必retain。另外,您应该使用属性设置器(self.searchResultFileSize = x;)而不是直接分配。然后,您在release中调用-dealloc

此外,

NSLog(@"Float filesize: %f", searchResultFileSize);

searchResultFileSizeNSNumber对象,您可以使用NSNumber格式说明符输出%@的值:

NSLog(@"Float filesize: %@", searchResultFileSize);