NSMutableData消失了

时间:2012-12-07 20:49:57

标签: ios nsmutabledata

在我的程序中,我有一个NSMutableData变量,它收集来自http://www.nhara.org/scored_races-2013.htm的信息。大约第三次从网站获取信息后,当它包含90810个字节时,它会消失或变为空,因为如果我打印一个NSString,它就是null。这是代码

- (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);

}

最让我困惑的是我的NSMutableData存储了数据,但在声称具有相同的字节数时丢失了它。

NSMutableData的大小是否存在约束,还是我的问题只是内存管理?

1 个答案:

答案 0 :(得分:1)

您需要为xmlData变量创建一个属性。在您的头文件中  @interface MyClass,像这样做一个

@property (nonatomic, retain) NSMutableData * xmlData;

如果您正在使用ARC,那么如果您使用ARC以下,则保持强度保留。如果您想使用变量,请执行self.xmlData