Objective-C/cocoa 丢失数组值

发布于 2024-09-06 20:42:58 字数 434 浏览 1 评论 0原文

我有多个数组,但是,它们不会保留数据以供其他方法使用。

这是我的设置方式(简化)

.h

NSArray *array;
@property (nonatomic, copy) NSArray *array;
-(void)someMethod:(NSArray*)someArray;
-(void)heresNewMethod;

.m

-(void)someMethod:(NSArray*)someArray
 {
array = [someArray copy];
 }
-(void)heresNewMethod //gets called by method not shown
 {
  NSLog(@"%@", array);
 }

I have multiple arrays, however, they are not retaining their data for use in another method.

Here's how I have it set up (simplified)

.h

NSArray *array;
@property (nonatomic, copy) NSArray *array;
-(void)someMethod:(NSArray*)someArray;
-(void)heresNewMethod;

.m

-(void)someMethod:(NSArray*)someArray
 {
array = [someArray copy];
 }
-(void)heresNewMethod //gets called by method not shown
 {
  NSLog(@"%@", array);
 }

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

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

发布评论

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

评论(3

冰火雁神 2024-09-13 20:42:58

发生了以下两件事之一:

  • 您向对象发送了一条 someMethod: 消息,传递了 nil (可能无意)。发送到 nil 的消息返回 nil,因此您将 nil(作为 copy 消息的结果)分配给数组实例变量。即使您之前已经在那里存储了指向数组的指针,您也会在对此 someMethod: 消息的响应中将其替换为 nil
  • 您从未向对象发送 someMethod: 消息。由于实例变量被初始化为nil,并且您从未在array实例变量中放置任何不同的内容,因此它仍然包含nil

在代码中添加更多 NSLog 语句来测试第一个理论。事实要么是其中之一,要么是另一个,因此证实第一个理论就反驳了第二个理论,反之亦然。

One of two things happened:

  • You sent the object a someMethod: message, passing nil (probably without meaning to). A message to nil returns nil, so you assigned nil—as the result of the copy message—to the array instance variable. Even if you had stashed a pointer to an array there previously, you replaced it with nil in your response to this someMethod: message.
  • You never sent the object a someMethod: message. Since instance variables are initialized to nil, and you never put anything different in the array instance variable, it still contains nil.

Sprinkle more NSLog statements in your code to test the first theory. The truth is either one or the other, so confirming the first theory disproves the second, and vice versa.

独木成林 2024-09-13 20:42:58

除了每次调用 someMethod: 时都会泄漏 array 中的内容之外,该代码应该可以工作。您看到什么问题?

Except for the fact that you'll leak whatever was in array every time you call someMethod:, that code should work. What's the problem you see?

鲜血染红嫁衣 2024-09-13 20:42:58

唯一的答案是您提供的代码不是您使用的代码,区别是至关重要的。我的意思是,您声明了一个随后不使用的属性,并且不清楚您是否正确定义了访问器,或者数组是否也是一个隐藏您的属性的本地变量,或者什么。

请发布您的真实代码。

The only answer is that the code you provided is not the code your using, and the difference is crucial. I mean, you declare a property which you then don't use, and it's not clear whether you are defining your accessors properly, or if array is also a local which is shadowing your property, or what.

Please post your real code.

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