【问题标题】:NSMutableData disappearingNSMutableData 消失
【发布时间】:2012-12-07 20:49:57
【问题描述】:

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

- (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 的大小是否有限制,还是我的问题只是内存管理?

【问题讨论】:

  • 猜测您正在使用 ARC。您的变量正在被释放。将其声明为具有强属性的@property。
  • @Rog 他没有使用 ARC - 请参阅对 autorelease 的调用?
  • 您在哪里看到问题?在didReceiveData 方法或didFinishLoading 方法中?转换部分数据(在 didReceiveData 中)可能会导致 nil 字符串,因为此时部分数据不是有效的 UTF8 字符串。
  • 问题出在didReceiveData

标签: ios nsmutabledata


【解决方案1】:

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

@property (nonatomic, retain) NSMutableData * xmlData;

如果您使用 ARC,则将其保留为强,如果您使用低于 ARC,则将强更改为保留。当你想使用你的变量时,你可以self.xmlData

【讨论】:

  • 为什么你认为属性是必要的?它不是。此外,如果这是问题所在,为什么这会在前几次起作用?
  • 如果我错了请纠正我,但我的印象是方法中设置的变量不能在方法范围之外使用。他显然将xmlData 设置为viewWillAppear 中的变量。如果您不为其创建属性,他将如何通过其他方法访问该变量?
  • 不,xmlData 显然不是viewWillAppear: 的局部变量,因为viewWillAppear: 中没有变量声明。因此,它必须是实例变量(或全局但不太可能)。
  • 忘了说 xmlData 是一个实例变量
猜你喜欢
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多