gpt4 book ai didi

ios - 我们如何在不同的 UIView 类中访问添加到 viewcontroller 类中的数组的值?

转载 作者:行者123 更新时间:2023-11-28 20:23:33 25 4
gpt4 key购买 nike

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的其他帖子,只在viewcontrollers之间提到了传值;或者数组在 appdelegate 中声明并在类中使用(我想避免)。

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

最佳答案

您可以在您的 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
)

关于ios - 我们如何在不同的 UIView 类中访问添加到 viewcontroller 类中的数组的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14982298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com