Objective-C/cocoa 丢失数组值
我有多个数组,但是,它们不会保留数据以供其他方法使用。
这是我的设置方式(简化)
.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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
发生了以下两件事之一:
someMethod:
消息,传递了nil
(可能无意)。发送到nil
的消息返回nil
,因此您将nil
(作为copy
消息的结果)分配给数组
实例变量。即使您之前已经在那里存储了指向数组的指针,您也会在对此someMethod:
消息的响应中将其替换为nil
。someMethod:
消息。由于实例变量被初始化为nil
,并且您从未在array
实例变量中放置任何不同的内容,因此它仍然包含nil
。在代码中添加更多 NSLog 语句来测试第一个理论。事实要么是其中之一,要么是另一个,因此证实第一个理论就反驳了第二个理论,反之亦然。
One of two things happened:
someMethod:
message, passingnil
(probably without meaning to). A message tonil
returnsnil
, so you assignednil
—as the result of thecopy
message—to thearray
instance variable. Even if you had stashed a pointer to an array there previously, you replaced it withnil
in your response to thissomeMethod:
message.someMethod:
message. Since instance variables are initialized tonil
, and you never put anything different in thearray
instance variable, it still containsnil
.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.
除了每次调用
someMethod:
时都会泄漏array
中的内容之外,该代码应该可以工作。您看到什么问题?Except for the fact that you'll leak whatever was in
array
every time you callsomeMethod:
, that code should work. What's the problem you see?唯一的答案是您提供的代码不是您使用的代码,区别是至关重要的。我的意思是,您声明了一个随后不使用的属性,并且不清楚您是否正确定义了访问器,或者数组是否也是一个隐藏您的属性的本地变量,或者什么。
请发布您的真实代码。
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.