我无法理解如何初始化类并将相同的init参数传递给多个实例。我可以使用1个插座(instance1)。但是,如何在不重写每个实例的变量的情况下让它与实例2一起工作呢?
ViewController.h:
#import "CustomClass.h"
@interface MYViewController : UIViewController
@property (unsafe_unretained, nonatomic) IBOutlet CustomClass *instance1;
@property (unsafe_unretained, nonatomic) IBOutlet CustomClass *instance2;
@end
ViewController.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];
答案 0 :(得分:0)
实际上,您希望将实例添加到NSSet或NSArray并迭代它或使用Key-Value Coding来设置值。如果这些出口在概念上是一组事物而不仅仅是一堆碰巧具有相同初始值的独立对象,那么您可以使用IBOutletCollection而不是IBOutlet将它们全部保存在数组中以开始。
答案 1 :(得分: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;
}
}
应该非常接近你正在寻找的东西。