1

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.

1
  • As Dave says, the setter approach is correct. However one thing to note is you should make sure to stop the previous player (if there was one) before creating another in the setter. Commented Feb 14, 2016 at 22:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks. I thought it wasn't the correct way of doing things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.