gpt4 book ai didi

ios - 从 NSMutableArray 检索后 NSURL 不起作用

转载 作者:行者123 更新时间:2023-11-29 04:23:42 25 4
gpt4 key购买 nike

在将录音文件地址存储在数组中并稍后使用时遇到问题。这就是我获取 URL 地址、将其转换为字符串并将其添加到数组中的方法。这似乎有效。

testViewController.h

@interface record_audio_testViewController : UIViewController <AVAudioRecorderDelegate> {       
NSURL *audioFile;
AVAudioRecorder *recorder;
...
}
@property (nonatomic, retain) NSURL *audioFile;

testViewController.m

#import "record_audio_testViewController.h"
@implementation record_audio_testViewController
@synthesize audioFile

- (void)viewDidLoad {
NSMutableArray *urlArray = [[NSMutableArray alloc] init];
audioFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];
// convert NSURL to NSString
NSString *fileLoc = [audioFile absoluteString];
[urlArray addObject: fileLoc ];
[[NSUserDefaults standardUserDefaults] setObject:urlArray forKey:@"urlArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
[urlArray release];
// Create an AVAudioSession object.
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: &error];
//Activate the session
[audioSession setActive:YES error: &error];
}

- (void)buttonClicked:(UIButton*)button {
NSMutableArray *urlArray;
urlArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"urlArray"];
audioFile = [NSURL URLWithString: [urlArray objectAtIndex:btnN] ];
// at this point, the URL looks exactly as created
}

- (IBAction)  rec_button_pressed {
NSMutableDictionary* recordSetting = [[NSMutableDictionary alloc] init];
[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
recorder = [[ AVAudioRecorder alloc] initWithURL: audioFile settings: recordSetting error:&error ]; // this is where it CRASHES

[recorder setDelegate:self];
[recorder prepareToRecord];
[recorder record];
}

当我使用 NSLog 查看并比较这些地址时,它们看起来都一样。但程序抛出异常:

    Thread 1: EXC_BAD_ACCESS (code=2 address=0x9)

有谁知道如何度过这种情况吗?另外,有没有更简单和/或更安全的方法来做到这一点?

最佳答案

您显示的代码可能完全不相关,因为这里不抛出异常。该异常可能是由于内存管理错误造成的,并且可能与 NSURL 无关。您只是在猜测 - 而且您不应该这样做。

您的代码中没有内存管理,并且由于您没有使用 ARC,这表明您不知道自己的内存管理职责。我的书向您解释了它们,并且还解释了为什么您应该使用 ARC(如果可以的话):

http://www.apeth.com/iOSBook/ch12.html

另外,使用静态分析器;它会发现内存管理不善的一些危险迹象。

关于ios - 从 NSMutableArray 检索后 NSURL 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12649615/

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