Vimy
Vimy

Reputation: 130

init UIView with custom parameters

I'm trying to pass data to a custom uiview when initing. I followed the method outlined here.

My UIView

-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if(self = [super initWithCoder:aDecoder])
    {
        [self initAudioPlayer];
    }

    return self;
}

- (void)initAudioPlayer
{
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.fileURL error:nil];
    [self.player prepareToPlay];

}

My ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.audioURL = [[NSBundle mainBundle] URLForResource:@"audio4" withExtension:@"wav"];
    AudioControlsView *view = [[[NSBundle mainBundle] loadNibNamed:@"AudioControlView"
                                                 owner:self
                                                options:nil] objectAtIndex:0];
    if (view)
    {    
            view.fileURL = self.audioURL;
    }
 [self.view addSubview:view];

}

When I do it this fileURL is nil.

I can get it to work with:

- (void)setFileURL:(NSURL *)fileURL
{
    _fileURL = fileURL;
    self.player = [[AVAudioPlayer alloc]initWithContentsOfURL:self.fileURL error:nil];
    [self.player prepareToPlay];
}

But I don't think that's the proper way.

Upvotes: 1

Views: 321

Answers (1)

Dave Batton
Dave Batton

Reputation: 8845

With the code you have now, -initAudioPlayer gets called before you set the fileURL.

I'd remove -initAudioPlayer and all of the init code. Your -setFileURL: accessor method is the correct approach.

Upvotes: 2

Related Questions