【问题标题】:How to retain variable in arc in every class如何在每个类的弧中保留变量
【发布时间】:2026-01-29 17:20:08
【问题描述】:

我有很多发送请求的类,最后都发送到SplitViewController。在SplitUIviewclass 中,我必须长时间轮询并将数据写入表格视图。长轮询是在后台线程中完成的,所以我在应用程序委托中声明了一个变量,但当涉及到它时,它是nil。问题是每当我尝试通过appdelegate 访问NSMutablearray 时,它都会以nil 的形式出现,并且该数组正在被释放。我的长轮询代码是

- (void) longPoll {

@autoreleasePool
{
//compose the request
NSError* error = nil;
NSURLResponse* response = nil;
NSURL* requestUrl = [NSURL URLWithString:@"http://www.example.com/pollUrl"];
NSURLRequest* request = [NSURLRequest requestWithURL:requestUrl];

//send the request (will block until a response comes back)
NSData* responseData = [NSURLConnection sendSynchronousRequest:request
                        returningResponse:&response error:&error];

//pass the response on to the handler (can also check for errors here, if you want)
[self performSelectorOnMainThread:@selector(dataReceived:) 
      withObject:responseData waitUntilDone:YES];
}



//send the next poll request
[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) startPoll {

[self performSelectorInBackground:@selector(longPoll) withObject: nil];
}

- (void) dataReceived: (NSData*) theData {
//i write data received here to app delegate table
}

如果我从收到的数据中调用 SplitView 类中的任何其他方法,我将失去控制,我也无法在收到的数据或正在释放的变量中打印我的应用程序委托值,我无法调用重新加载表或任何其他方法在这里。

【问题讨论】:

  • 将您的属性设置为强/保留
  • 你能在 dataRecieved: 方法中打印“theData”吗?这是正确的吗?如果是这样,您需要发布更多代码。
  • 我可以打印 dataRecieved 中的 theData 并确保给我一些时间来发布完整的问题

标签: ios objective-c automatic-ref-counting long-polling


【解决方案1】:

你不能像这样在你的 ViewControllers 中设置你的属性作为强/保留

property (strong,retain) NSMutableArray *myData;

顺便说一句,我刚才了解到,将 AppDelegate 用作全局容器的存储位置是一种不好的做法。 ApplicationDelegate 是应用程序委托方法和应用程序基础初始设置的地方;比如设置navigationController。

因此,请考虑将您的数据存储在适当的位置,可能是核心数据或其他东西。

【讨论】:

    最近更新 更多