从另一个类访问 NSMutableArray
我有一个 NSMutableArray,我需要从另一个类访问它。这就是我到目前为止所做的;
我在
.h
文件中声明了NSMutableArray *muArr
,以及@property(nonatomic, keep) NSMutableArray *muArr
。@synthasize muArr;
在.m
文件中,最后填充它:[muArr addObject: @"First"];
现在在
SecondView
中我添加了导入语句#import "FirstView.h"并写道:
FirstView *frv = [[FirstView alloc]init];
然后NSLog(@"%i",[frv.muArr count]);
这几行代码写在viewDidLoad
方法中。当打印 NSLog
时,我得到了 0
记录而不是 1
。
这是为什么呢?我做错了什么,有人可以给我看示例代码/教程吗?
I have a NSMutableArray
and I need to access it from another class. This is what I have done so far;
I declared
NSMutableArray *muArr
in the.h
file, and@property(nonatomic, retain) NSMutableArray *muArr
.@synthasize muArr;
in the.m
file, and finally populated it:[muArr addObject: @"First"];
Now in
SecondView
I added the import statement#import "FirstView.h"
and wrote:FirstView *frv = [[FirstView alloc]init];
thenNSLog(@"%i",[frv.muArr count]);
These lines of code are written in the viewDidLoad
method. and when the NSLog
was printed I got 0
records instead of 1
.
Why is this? what have I done wrong, and can someone show me a sample code/tutorial?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在
didSelectRowAtIndexPath
中填充muArr
,在您选择一行之前不会调用它。通过在 FirstView 上调用init
,您可以创建一个新的 FirstView,然后立即检查muArr
的计数。计数为 0,因为您尚未选择任何行..You are populating
muArr
indidSelectRowAtIndexPath
, which doesn't get called until you select a row. By callinginit
on your FirstView, you create a new FirstView then immediately check the count ofmuArr
. The count is 0, because you haven't selected any rows yet..您需要在 SecondView 类中创建一个属性(与创建 muArr 的方式相同)
步骤 1) :假设 arrOfSecondView 并合成它
步骤 2) 现在您可以将 muArr 数据添加到 arrOfSecondView
步骤 3) 检查 arrOfFirstView 计数
You need to create a property(in the same fashion as you create muArr) in SecondView class
Step 1) : Lets say arrOfSecondView and you synthesize it
Step 2) Now you can add your muArr data to arrOfSecondView
Step 3) Check the arrOfFirstView count
你分配数组吗?在向其中添加项目之前,必须使用分配它。
如果不这样做, [addObject] 调用不会使程序崩溃,但不会产生任何效果。并且数组的
count
将永远保持为零。@synthesize 与普遍的看法相反,它不分配 ivar。它只是在类中生成一个 getter 方法和一个可选的 setter 方法。
Do you allocate the array? Before you add items to it, you have to allocate it with
If you don't do that, the [addObject] call will not crash the program, but won't have any effect. And array's
count
will remain zero forever.@synthesize, contrary to a popular belief, does not allocate the ivar. It just generates a getter method and, optionally, a setter method in the class.