Search code examples
releasescrollviewautomatic-ref-countingretainsubviews

ARC - inserting multiple subviews and handle actions


I have some problems with ARC. I'm trying to add multiples views to a ScrollView, and after that if the user tap one view will call a action.

But when user tap the view i get this message: "message sent to deallocated instance"

How can i retain the views?

this is my code in 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)];
}

Solution

  • You need to hold reference to all ChannelViewController instances in your ViewController. In your code, after each for loop iteration, ARC releases your ChannelViewController instance. The simplest way to avoid this is to prepare an array property in 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)];
    }