2012-12-07 37 views
0

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

- (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的大小约束或是我的问题只是内存管理?

+0

猜测你正在使用ARC。你的变量正在被分配。将它声明为拥有强大属性的@property。 – Rog

+0

@Rog他没有使用ARC--看到对'autorelease'的调用? – rmaddy

+0

你在哪里看到这个问题?在'didReceiveData'方法或'didFinishLoading'方法中?转换部分数据(在'didReceiveData'中)可能会导致一个'nil'字符串,因为此时部分数据不是有效的UTF8字符串。 – rmaddy

回答

1

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

@property (nonatomic, retain) NSMutableData * xmlData; 

如果您正在使用ARC你,如果你使用下面的ARC更改强烈保留离开它一样强烈。当你想使用你的变量你做self.xmlData

+0

为什么你认为一个属性是必要的?不是。此外,如果这是问题,那么为什么这会在前几次工作? – rmaddy

+0

如果我错了,请纠正我,但我的印象是方法中设置的变量不能在方法范围之外使用。他清楚地在'viewWillAppear'中将'xmlData'设置为一个变量。如果您不为其创建属性,他将如何使用其他方法访问该变量? –

+0

不,'xmlData'显然不是'viewWillAppear:'的局部变量,因为'viewWillAppear:'中没有变量声明。因此,它必须是一个实例变量(或全局的,但不太可能)。 – rmaddy