在将音频录制文件地址存储在阵列中并稍后使用时遇到问题。 这是我获取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)
任何人都知道如何度过这种情况? 此外,有更简单和/或更安全的方法吗?
答案 0 :(得分:1)
您展示的代码可能完全不相关,因为抛出异常不在此处。异常可能是由于内存管理错误,可能与NSURL无关。你只是在猜测 - 你不应该这样做。
您的代码中没有内存管理,因为您没有使用ARC,这表明您不了解您的内存管理职责。我的书向您解释了这些内容,并解释了为什么您应该使用ARC:
http://www.apeth.com/iOSBook/ch12.html
另外,使用静态分析仪;它会发现记忆管理不善的一些危险迹象。