在我的程序中,我有一个NSMutableData变量,它从http://www.nhara.org/scored_races-2013.htm收集信息。在大约第三次从网站获取信息之后,当它包含90810字节时,它消失了或变为null,因为如果我将其打印为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的大小是否受到限制?或者我的问题仅仅是内存管理吗?

最佳答案

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

@property (nonatomic, retain) NSMutableData * xmlData;


如果您使用的是ARC,则将其保留为坚固,如果使用的是低于ARC,则将其更改为保留。当您想使用变量时,请执行self.xmlData

关于ios - NSMutableData消失,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13770770/

10-10 19:46