Objective-C - Program received signal: “EXC_BAD_ACCESS”. with (NSNumber floatValue)
I am getting a Program received signal: “EXC_BAD_ACCESS”.
when using the following code.
searchResultFileSize
is declared as an NSNumber
in my interface. I wasn't sure what property to set it as. Currently I have it as:
@property (nonatomic, readonly) NSNumber *searchResultFileSize;
Is this correct? I get the errors on the following lines:
NSLog(@"float filesize: %f", [searchResultFileSize floatValue]); //Program received signal: “EXC_BAD_ACCESS”.
HUD.progress = [resourceLength floatValue] / [searchResultFileSize floatValue]; //Program received signal: “EXC_BAD_ACCESS”.
If I comment out the first line it still obviously fails on the second. Any ideas what the problem could be? Perhaps my conversions are wrong. Here are the two methods where I am using this piece of code:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
searchResultFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
NSLog(@"Float filesize: %f", searchResultFileSize);
if ([searchResultFileSize intValue]开发者_StackOverflow社区 != 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]);
}
Your problem is here:
searchResultFileSize = [NSNumber numberWithLongLong:[response expectedContentLength]];
You need to retain
it to keep it around, it is autoreleased.
searchResultFileSize = [[NSNumber numberWithLongLong:[response expectedContentLength]] retain];
I would suggest setting your property as (nonatomic, retain)
, then you won't have to retain
it in your code. Plus, you should use the property setters (self.searchResultFileSize = x;
) as opposed to direct assignment. Then you'd invoke release
in -dealloc
.
Also,
NSLog(@"Float filesize: %f", searchResultFileSize);
searchResultFileSize
is a NSNumber
object, you can output the value of an NSNumber
using the %@
format specifier:
NSLog(@"Float filesize: %@", searchResultFileSize);
精彩评论