我有 2 个类,比如 A 和 B。 我在 A 类中有一个可变数组 _arrayOfPaths 现在我正在尝试访问类 b 中的该数组。 如下所示:
A *testModel = [[A alloc]init];
NSMutableArray *array = [testModel.arrayOfPaths mutableCopy];
现在,当我 NSLog
这个新创建的数组时,它显示为 null。
如果我打印 testModel.arrayOfPaths
那么它也会显示 null。
我的问题是:
- 为什么显示为空?
- 如何在 B 类中访问
_arrayOfPaths
? - 我需要为此使用继承吗? B已经继承
UITableViewController
。 - objective-c 是否支持多重继承?
最佳答案
<强>1。在这里,您只是创建一个新的 A 实例,而不是访问 A 的现有实例以获取 B 实例中的数组。所以只有它显示空值。
<强>2。请参阅此代码以解决第二个问题....
ClassA.h
@interface ClassA:UIViewController
@property (nonatomic, retain) NSMutableArray *arrayOfPaths;
@end
ClassA.m
@implementation ClassA
@synthesize arrayOfPaths = _arrayOfPaths;
-(id)init
{
self = [super init];
if(self)
{
self.arrayOfPaths = [[NSMutableArray alloc] initWithObjects:@"1",@"2", nil];
//Delegation process
ClassB *bInstance = [[ClassB alloc] init];
[bInstance setAReference:self];
//Do your stuff of presenting ClassB instance here.....
}
}
@end
ClassB.h
#import "ClassA.h"
@interface ClassB:UITableViewController
@property (nonatomic, copy) ClassA *aReference;
@end
ClassB.m
@implementation ClassB
@synthesize aReference = _aReference;
-(void)viewDidLoad
{
NSLog(@"Array from class ClassA %@", self.aReference.arrayOfPaths);
}
@end
ClassB ViewController 应该只在此处由 ClassA 实例化。
<强>3。您需要使用委托(delegate)概念来实现您的要求。参见上面的示例代码
<强>4。 objective -c 不支持多重继承。
关于ios - 访问另一个类中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15678699/