NSURLConnection 保存变量不起作用

发布于 2024-10-24 12:44:53 字数 414 浏览 2 评论 0原文

我正在发出(异步)url 请求。

在委托函数connectionDidFinishLoading中,我将服务器的响应分配给实例变量。

提出请求后,我等待几秒钟,我确信我已收到响应。

我有一个链接到 IBAction 的按钮,该按钮将该变量打印到 NSLog,但它始终为 null。

我不知道发生了什么事。 url 请求是否启动了一个新线程,并且保存的任何变量都无法在主线程中访问......或者为什么我根本看不到任何保存的变量。

我可以在 connectionDidFinishLoading 中正确使用接收到的数据,但是当我将此数据分配给实例变量并尝试在函数外部访问它们时,它们始终为空。

长话短说 我到底如何保存响应或 URL 请求以供以后使用!?!

提前致谢。

I am making an (asynchronous) url request.

In the delegate function connectionDidFinishLoading I assign the response of the server to an instance variable.

I wait a few seconds after I make the request and I am SURE that I have received the response.

I have a button linked to an IBAction which prints out this variable to NSLog, but it is ALWAYS null.

I have no idea what's going on. Does the url request start a new thread and any of the variables saved, aren't accessible in the main thread... or why on earth can I not ever see any of my saved variables.

I can properly use the received data inside the connectionDidFinishLoading, but when I assign this data to instance variables and try to access them outside the function they are always null.

TL;DR
How on earth do I save the responses or a url request for later use!?!

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶情人眼里出诗心の 2024-10-31 12:44:53

问题可能是您没有保留内存,因此它被自动释放。您正在分配的实例变量是否是指定了“保留”或“复制”的属性?您还可以在设置对象本身后手动调用保留:

[myString retain];

使用属性是更好的管理方式,例如 .H:

@interface MyClass: Object    {
    NSString *myString;
}
@property (nonatomic, retain) NSString *myString;

.M 中的其他位置:

@synthesize myString    
...
...
self.myString = ...

这可以确保在您想要执行以下操作之前不会释放字符串:

[myString release];
self.myString = NULL;

The problem may be that you are not retaining the memory so it is being automatically freed. The instance variable you are assigning, is it a property with "retain" or "copy" specified? You can also manually call retain on the object itself after you set it:

[myString retain];

Using a property is a better way to manage, example .H:

@interface MyClass: Object    {
    NSString *myString;
}
@property (nonatomic, retain) NSString *myString;

elsewhere in .M:

@synthesize myString    
...
...
self.myString = ...

This ensures the string is not released on you until you want to:

[myString release];
self.myString = NULL;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文