Variable issue during transition from iOS 4 to iOS

2019-08-03 06:57发布

The "old" way that I was doing this in iOS 4 was by declaring the object in the header file and passing the object for a write-back to handle an error parameter.

NSError *error;

For reasons beyond my limited knowledge I could not continue this pattern in iOS5 and received the error:

"Passing address of non-local object to _autoreleasing parameter for write-back"

//Instantiate an instance of AVAudioSession object
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//Setup playback and Record
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error ];

The temporary solution for me is to do this:

NSError *theError = nil;

//Instanciste an instance of AVAudioSession object
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//Setup playback and Record
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&theError];
//Activate session
[audioSession setActive:YES error:&theError];

This is annoying as I have to create this local object each time I need to use it in Xcode.

My question is: Is there a better way of doing this in the new ARC paradigm?

I found a similar question here in stack overflow that deals with this issue sort of... here

1条回答
狗以群分
2楼-- · 2019-08-03 07:43

The preferred way to handle this situation in the event you actually wanted to use the ivar NSError *error would be:

NSError *theError = nil;
    //...
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&theError];
if (theError != nil){
    error = theError;
    //Handle failure
}
[audioSession setActive:YES error:&theError];
if (theError != nil){
    error = theError;
    //Handle failure
}

My guess is that you mean to ignore the errors entirely, forgive me if I'm wrong. That can be done by simply doing this (though not recommended):

[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession setActive:YES error:nil];
查看更多
登录 后发表回答