ios - 将对象添加到NSMutableArray时抛出EXC_BAD_ACCESS

标签 ios nsmutablearray exc-bad-access

尝试将对象添加到数组时出现EXC_BAD_ACCESS错误。我知道这可能意味着我指向的是内存中不存在的东西,或者这些对象包含nil值。

码:

- (void)fadeInPlayer:(AVAudioPlayer *)player withMaxVolume:(float)maxVolume {

NSLog(@"player: %@", player);
NSLog(@"maxVolume: %f", maxVolume);

NSMutableArray *playerAndVolume = [NSMutableArray arrayWithObjects: player, maxVolume, nil];

if (player.volume <= maxVolume) {
    player.volume = player.volume + 0.1;
    NSLog(@"%@ Fading In", player);
    NSLog(@"Volume %f", player.volume);
    [self performSelector:@selector(fadeInPlayer:withMaxVolume:) withObject:playerAndVolume afterDelay:0.5];
    //playerAndVolume array used here because performSelector can only accept one argument with a delay and I am using two...
    }

}

奇怪的是,当我打印要添加到控制台的对象时(上面显示为NSLogs),它们返回数据:
player: <AVAudioPlayer: 0x913f030>
maxVolume: 0.900000

该应用程序在NSLogs之后立即崩溃。其余代码无需数组即可正常工作,但我需要使用它来调用该方法上的performselector:withObject:AfterDelay。

因此,如何初始化数组或对象类型肯定存在问题,但我无法弄清楚。

任何帮助表示赞赏。

最佳答案

您不能将float添加到NSArray。您必须将其包装在NSNumber中。



真正的问题是,传入的第一个参数是您创建的NSArray,传入函数中的第二个参数是支持NSTimer方法的performSelector:afterDelay:...。它不会散布数组中的对象,而只是将数组作为第一个参数传递。如果您坚持使用API设计,则需要测试第一个参数的类,以查看它是NSArray还是AVAudioPlayer。您可以这样实现此功能:

-(void)fadeInPlayer:(AVAudioPlayer *)player withMaxVolume:(NSNumber *)maxVolume {
    if ([player isKindOfClass:[NSArray class]]){
        // This is a redundant self call, and the player and max volume are in the array.
        // So let's unpack them.
        NSArray *context = (NSArray *)player;
        player = [context objectAtIndex:0];
        maxVolume = [context objectAtIndex:1];
    } 

    NSLog(@"fading in player:%@ at volume:%f to volume:%f",player,player.volume,maxVolume.floatValue);

    if (maxVolume.floatValue == player.volume || maxVolume.floatValue > 1.0) return;

    float newVolume =  player.volume + 0.1;
    if (newVolume > 1.0) newVolume = 1.0;
    player.volume = newVolume;

    if (newVolume < maxVolume.floatValue){
        NSArray *playerAndVolume = [NSArray arrayWithObjects: player, maxVolume, nil];
        [self performSelector:@selector(fadeInPlayer:withMaxVolume:) withObject:playerAndVolume afterDelay:0.5];
    }
}

您将使用此方法,将float包装在NSNumber中,如下所示:
[self fadeInPlayer:player withMaxVolume:[NSNumber numberWithFloat:1.0]];

请注意,这将被认为是一个非常奇怪的函数,但是此代码可以运行。

关于ios - 将对象添加到NSMutableArray时抛出EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14096421/

相关文章:

iOS - cellForRowAtIndexPath 代码解释

ios - 订购带日期的 NSMutableArray

ios - 如何将多个数组加载到 UITableView 中?

Swift set delegate to self 给出 EXC_BAD_ACCESS

ios - CGImageRef 出现 EXC_BAD_ACCESS 错误

iphone - 带有动画启动画面的iPhone/iPad应用

ruby-on-rails - 图像处理 rails + iOS 核心数据

java - BufferedReader 没有从 LXSocket 接收字符串

ios - AVAudioRecorder.record() 在 iOS 8 中总是返回 "false"

objective-c - 在 Objective c 中管理内存