我有30个UILabels,我希望用作IBOutlets。但是,当我尝试访问他们的 UILabel 属性时,我收到错误,告诉我找不到类型为"id"的对象的属性 x。我对目标C非常生疏,所以怀疑我做了一些根本上错误的事情。我已经将所有标签分配给 xib 文件中的 IBCollection。
.h
@interface ViewController : UIViewController
{
IBOutletCollection(UILabel) NSArray *statPanels;
}
@property(retain) IBOutletCollection(UILabel) NSArray *statPanels;
@end
.m
@interface ViewController ()
@end
@implementation ViewController
@synthesize statPanels;
- (void)viewDidLoad
{
[super viewDidLoad];
statPanels = [[NSArray alloc] initWithObjects:[UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], nil ];
[statPanels objectAtIndex:3].hidden = YES;
}
如果您在界面生成器中连接了所有标签,则不必初始化statPanels
数组。
删除此行:
statPanels = [[NSArray alloc] initWithObjects:[UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], nil ];
这条线正在创建一个新的数组和一堆新的标签,并失去你的出口。
此外,您需要像另一个答案所说的那样投射:
((UILabel *) [statPanels objectAtIndex:3]).property = ....
我认为你应该使用cast; NSArray
只知道它包含一堆id
。所以你需要做一些类似的事情
((UILabel *)[array objectAtIndex:0]).someProperty
此外,您应该拥有alloc init
,而不仅仅是alloc
。同样在你的 ivar 声明中,你不需要IBOutlet...
和东西。只是NSArray
.(在相对较新的XCode版本中,您根本不需要声明ivar。
当 nib 被反序列化时,其中指定的对象将被实例化并分配给它们的出口。 您不必自己实例化对象,这样做将失去对相关标签的唯一引用。
基本上,您只需要删除此行:
statPanels = [[NSArray alloc] initWithObjects:[UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], [UILabel alloc], nil ];
您还应该知道,在不调用任何初始化器的情况下分配对象注定会以糟糕的方式结束。 你不应该这样做。 Objective-C中通常的模式是调用[[Foo alloc] init]
或类似。