0

我有 30 个 UILabel 我希望用作 IBOutlets。但是,当我尝试访问他们的 UILabel 属性时,我收到错误消息,告诉我没有为“id”类型的对象找到属性 x。我对Objective 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;
}
4

3 回答 3

3

如果您在界面生成器中连接了所有标签,那么您不必初始化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 = ....
于 2012-08-15T20:20:08.743 回答
1

我认为你应该使用 cast;NSArray只知道它包含一堆id's。所以你需要做类似的事情

((UILabel *)[array objectAtIndex:0]).someProperty

此外,您应该拥有alloc init而不是仅拥有alloc. 同样在您的 ivar 声明中,您不需要IBOutlet...和东西。只是NSArray。(在相对较新的 XCode 版本中,您根本不需要声明 ivar。)

于 2012-08-15T20:15:15.830 回答
0

当 nib 被反序列化时,它们中指定的对象被实例化并分配给它们的 outlet。您不必自己实例化对象,这样做会失去对相关标签的唯一引用。

基本上,你只需要删除这一行:

    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]或类似的。

于 2012-08-15T20:24:56.577 回答