gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:25:34 25 4
gpt4 key购买 nike

尝试将对象添加到数组时出现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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com