【问题标题】:How to reference object without using property or ivar如何在不使用属性或 ivar 的情况下引用对象
【发布时间】:2012-03-29 17:06:59
【问题描述】:

如果我使用以下方法在 subviews 集合中添加 UIView 子类:

-(void)loadOutlet
{
    myOutlet *out = [[myOutlet alloc] init];
    [self addSubview:out];
    [out release];
}

-(void)unloadOutlet
{
    myOutlet *out = <<HOW CAN I REFERENCE IT FROM subviews array?>>
    [out removeFromSuperView];
}

这样做的最佳做法是什么?

从现在开始,我使用 isKindOfClass 为每个子视图查找使用循环,但是没有更好的方法吗?

谢谢。

【问题讨论】:

  • 因为我不喜欢在加载视图时声明将在内存中的属性。在这种情况下,我有一些在主视图生命周期中加载和卸载的子视图。

标签: objective-c ios object


【解决方案1】:

您可以为子视图分配一个标签,然后使用相同的标签检索它。

-(void)loadOutlet
{
    myOutlet *out = [[myOutlet alloc] init];
    out.tag = 1; // Or some other value
    [self addSubview:out];
    [out release];
}

-(void)unloadOutlet
{
    myOutlet *out = [self viewWithTag:1];
    [out removeFromSuperView];
}

【讨论】:

    【解决方案2】:

    或者:

    NSArray *currentSubViews = [self.subviews copy];
    
    // Loop through each subview
    for (id subview in currentSubViews) {
    
        // Check the Objective-C class of this object
        if ([subview isKindOfClass:[myOutlet class]]) {
    
            // Remove the superview
            [subview removeFromSuperView];
        }
    }
    

    Objective-C 的动态特性是一个很棒的工具。

    【讨论】:

    • 您好,感谢您的回答,但正如我在帖子中评论的那样,这与我从现在开始一直遵循的方法完全相同。
    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    相关资源
    最近更新 更多