0

我很难弄清楚如何初始化一个类并将相同的初始化参数传递给多个实例。我可以让它与 1 个插座(instance1)一起工作。但是我怎样才能让它在不为每个实例重写变量的情况下与实例 2 一起工作呢?

视图控制器.h:

#import "CustomClass.h"

@interface MYViewController : UIViewController

@property (unsafe_unretained, nonatomic) IBOutlet CustomClass *instance1;
@property (unsafe_unretained, nonatomic) IBOutlet CustomClass *instance2;

@end

视图控制器.m:

#import "CustomClass.h"

@implementation MYViewController;

@synthesize instance1, instance2;

- (void)viewDidLoad
{
    [super viewDidLoad];
    instance1.variable1 = option1;
    instance1.variable2 = 4.5;
    instance1.variable3 = instance1.value;
    [instance1 addTarget:self action:@selector(instance1DidChange) forControlEvents:UIControlEventValueChanged];
4

2 回答 2

0

本质上,您希望将实例添加到 NSSet 或 NSArray 并对其进行迭代或使用键值编码来设置值。如果这些出口在概念上是一组事物,而不仅仅是一堆碰巧具有相同初始值的独立对象,则可以使用 IBOutletCollection 而不是 IBOutlet 将它们全部保存在一个数组中。

于 2012-05-11T23:16:43.650 回答
0

带有一些 KVC 的循环应该为您完成...

@implementation MYViewController;

@synthesize instance1, instance2;

- (void)viewDidLoad
{
    [super viewDidLoad];

    for (int i = 0; i =< 1; i++) {
        MyClass *newInstanceVariable = [[MyClass alloc] init];
        newInstanceVariable.variable1 = option1;
        newInstanceVariable.variable2 = 4.5;
        newInstanceVariable.variable3 = instance1.value;
        [newInstanceVariable addTarget:self action:@selector(instance1DidChange) forControlEvents:UIControlEventValueChanged];
        instanceVariableName = [NSString stringWithFormat:@"instance%i",i];
        [self valueForKey:instanceVariableName] = newInstanceVariable;
    }
}

应该非常接近您要查找的内容。

于 2012-05-11T23:19:29.313 回答