0

viewcontroller.m 有以下代码

- (void)viewDidLoad
{
[super viewDidLoad];


self.array=[[NSArray alloc]initWithObjects:@"hi",@"hello", nil];
NSLog(@"%@",self.array);

view *view1=[[view alloc]init];
[view1 addSubview:self.view];
 view1.viewController=self;

}

还有另一个 UIView 类,我正在尝试访问数组:.h 文件:

#import <UIKit/UIKit.h>
#import "ViewController.h"

@class ViewController;

@interface view : UIView{
ViewController *viewController;


}
@property (nonatomic,retain)ViewController *viewController;


@end

和 .m 文件:

#import "view.h"
#import "ViewController.h"

@implementation view
@synthesize viewController;

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    NSLog(@"%@",[viewController array]);
}

return self;
}

我查看了stackoverflow的其他帖子,只提到了视图控制器之间的值传递;或者数组在 appdelegate 中声明并在类中使用(我想避免)。

上面最后一个代码段中的 NSLog 给出了 null;所以你能帮忙访问这个数组的值吗?提前致谢..!!

4

3 回答 3

2

您可以在 ViewController 中使用此代码来实现

#import "view.h"

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSArray *ary = [NSArray arrayWithObjects:@"7",@"5",@"3",@"2", nil];

    view *v=[[view alloc] init];
    [v initView:ary];

}

在您的 view.h 文件中:

#import <UIKit/UIKit.h>

@interface view : UIView

-(void)initView:(NSArray *)ary;
@end

在你的 .m 文件中:

#import "view.h"
#import "ViewController.h"

@implementation view

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

-(void)initView:(NSArray *)ary
{
    NSLog(@"%@",ary);
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

日志值将显示如下:

2013-02-20 20:11:52.731 SampleProject[9414:f803] (
    7,
    5,
    3,
    2
)
于 2013-02-20T14:48:32.713 回答
1

这条线

view *view1=[[view alloc]init];

initWithFrame:在您设置之前调用所需的初始化程序view1.viewController,所以发生的事情是

NSLog(@"%@",[viewController array]);

实际上调用

NSLog(@"%@",[null array]);

或(注意这是伪代码)

NSLog(@"%@",null);

您要做的是view1.viewController在分配后使用。最佳实践是制作一个自定义构造函数UIViewController*作为参数并使用它。

于 2013-02-20T14:39:49.707 回答
0

首先,您在视图上调用该方法并在从未调用过init的方法中检查 viewController 。initWithFrame(但也许您正在使用默认框架initWithFrame:从您的方法内部调用init。:))。其次,您在调用 init 方法
设置viewcontroller属性,因此您的方法中仍未初始化。第三,与其将整个 of 传递给您的视图来访问数组(这与 MVC 模式背道而驰),您可能只需在 UIView 子类中创建一个实例变量并仅传递数组即可。viewcontrollerinitWithFrameviewcontroller

然后你可以按照 Dilip 给出的答案,最好使用 setter 方法来设置数组。国际海事组织。

于 2013-02-21T06:40:19.380 回答