ios - 访问父数组不返回任何对象

标签 ios objective-c inheritance properties subclass

我一定是想多了 Objective-C 中这种简单的父类和子类通信。

我在父 View Controller 中创建并填充一个 NSMutableArray,然后在子类 View Controller 中我想访问该数组中的对象。 Xcode 没有抛出任何错误,但在子类中它没有在数组中找到任何对象。我做错了什么?

父类.h:

@interface ParentViewController : UIViewController
@property (strong, nonatomic) NSMutableArray *myArray;
@end

父类.m:

[self.myArray addObject:myString]; //add objects to array in a method

子类.h:

#import "ParentViewController.h"
@interface SubclassViewController : ParentViewController
@end

子类.m:

#import "SubclassController.h"
@implementation SubclassViewController
- (void)myMethod {
    NSLog(@"%d in parent array", [super.myArray count]); //always returns 0
}
@end

最佳答案

这取决于您将这一行放在代码中的什么位置(在哪个方法中):

[self.myArray addObject:myString]; //add objects to array in a method

例如,您可以将它放在 parentViewController 的 -viewDidLoad 方法中,如果您在 SubclassViewController 中调用 [super viewDidLoad](或者您没有实现 您的 SubclassViewController 中的 viewDidLoad 方法)它实际上会起作用。

问题是您混淆了一个类和一个对象: 您最终在屏幕上看到的是您的类 parentViewController 的一个实例 和您的类 SubclassViewController 的一个实例即它们是两个不同的对象。就像山姆和鲍勃是“人类”类的两个不同“对象”一样。现在他们都有一个属性 myArray - 就像 Sam 和 Bob 都拥有的列表。但由于他们是两个不同的人,他们也携带不同的名单。如果 Sam 在他的 list 上写了一些笔记,并不意味着这些笔记也会自动出现在 Bob 的 list 上。

关于ios - 访问父数组不返回任何对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21370999/

相关文章:

java - 使用仅在运行时可获得的静态类型

ios - 从 sqlite iOS 中选择数据有时有空语句

ios - 如何从字符串生成随机消息

ios - 这个效果叫什么?

ios - Firebase 刷新 token

c++ - 基类的多重虚继承和构造函数调用

c++ - 从模板继承 : scope error?

在移动 safari 中按下后退按钮后,Javascript 停止在 iframe 中执行

IOS查看容器: how to set the delegate

ios - 为我的 UITableViewCell 设置背景颜色不起作用