1

我对 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)];
}
4

1 回答 1

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)];
}
于 2011-12-26T04:05:37.437 回答