NSMutableData disappearing

2020-05-05 01:11发布

问题:

in my Program, I have a NSMutableData variable that collect the information from http://www.nhara.org/scored_races-2013.htm. After about the third time it gets information from a website, when it contains 90810 bytes, it either disappears or becomes null because if I print it a NSString, it is null. Here is the code

- (void)viewWillAppear:(BOOL)animated
{
    // Create a new data container for the stuff that comes back from the service
    xmlData = [[NSMutableData alloc] initWithCapacity:180000];

    [self fetchEntries];
    [super viewWillAppear:animated];
}
- (void)fetchEntries
{
        // Construct a URL that will ask the service for what you want 
    NSURL *url = [NSURL URLWithString: @"http://www.nhara.org/scored_races-2013.htm"];//

    // Put that URL into an NSURLRequest
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    // Create a connection that will exchange this request for data from the URL 
    connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data 
{
    // Add the incoming chunk of data to the container we are keeping 
    // The data always comes in the correct order 
    [xmlData appendData:data];

    NSLog(@"%@",xmlData);
    NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding]autorelease];
    NSLog(@"xmlCheck = %@", xmlCheck);

}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error= %@",error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {

    // We are just checking to make sure we are getting the XML 
    NSString *xmlCheck = [[[NSString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding] autorelease];
    NSLog(@"xmlCheck2 = %@", xmlCheck);

}

What confuses me the most is that my NSMutableData stores data, but then loses it while claiming to have the same number of bytes.

Is there a constraint to the NSMutableData's size or is my problem just memory management?

回答1:

You need to create a property for your xmlData variable. In your header file after your @interface MyClass, make one like so

@property (nonatomic, retain) NSMutableData * xmlData;

If you are using ARC you leave it as strong if you using below ARC you change strong to retain. When you want to use your variable you do self.xmlData