ARC - 插入多个子视图并处理操作

时间:2011-12-23 02:52:47

标签: release scrollview automatic-ref-counting retain subviews

我有一些ARC问题。我正在尝试将多个视图添加到ScrollView,之后如果用户点击一个视图将调用一个动作。

但是当用户点击视图时,我收到此消息:“消息已发送到解除分配的实例”

我如何保留观点?

这是我在ViewController中的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    int i;
    for (i=0;i<10;i++) {
        ChannelViewController *channelView = [[ChannelViewController alloc] init];
        [channelView.view setFrame:CGRectMake(i*175, 0, 175, 175)];
        //channelsScrollView is a ScrollView
        [self.channelsScrollView addSubview:channelView.view];
    }
    [self.channelsScrollView setContentSize:CGSizeMake(i*175, 175)];
}

1 个答案:

答案 0 :(得分:2)

您需要保持对ViewController中所有ChannelViewController实例的引用。在您的代码中,在每次for循环迭代之后,ARC会释放您的ChannelViewController实例。避免这种情况的最简单方法是在ViewController中准备一个数组属性。

// In ViewController.h
@property (nonatomic, retain) NSMutableArray * channelViews;

// In ViewController.m
@synthesize channelViews;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.channelViews = [[NSMutableArray alloc] initWithCapacity:10];

    // Do any additional setup after loading the view from its nib.
    int i;
    for (i=0;i<10;i++) {
        ChannelViewController *channelView = [[ChannelViewController alloc] init];
        [channelView.view setFrame:CGRectMake(i*175, 0, 175, 175)];
        //channelsScrollView is a ScrollView
        [self.channelsScrollView addSubview:channelView.view];
        [self.channelViews addObject:channelView];     // <-- Add channelView to the array
    }
    [self.channelsScrollView setContentSize:CGSizeMake(i*175, 175)];
}