1
我正在从服务器下载几个小尺寸歌曲并将其存储(NSData)到NSUserDefaults中,以便我可以在需要时使用它缓存并直接在设备上播放,而不是下载并从服务器再次播放。 问题是,如果我在NSUserDefaults中存储少量几个较小尺寸的歌曲作为数据格式,则会减少大量设备内存并引发内存警告或崩溃等。iPhone:在NSUserDefaults和内存问题上存储音频数据
难道你有人指导我如何解决它?如何将歌曲数据持久存储在设备上以实现缓存目的,并且同时以较少的内存使用量进行存储?
更新:根据建议,我试图将歌曲数据添加到字典作为文件,并试图检索它如下。但是,仍然面临着同样的问题,大约30mb的数据检索后的内存警告。有人可以帮我解决这个问题吗?我需要存储大约40 mb的歌曲数据并存储它。
NSURL *songurl = [NSURL URLWithString:downloadSOngUrl];
NSMutableData *songdata = [NSMutableData dataWithContentsOfURL:songurl];
NSString *fileName = [downloadSOngUrl lastPathComponent];
NSLog(@"fileName: %@",fileName);
[appDelegate writeSongIntoDocsDirectory :songdata :fileName];
-(void) writeSongIntoDocsDirectory :(NSData *) inSongData :(NSString *) songNamePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(@"songNamePath: %@", songNamePath);
songNamePath = [songNamePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
NSLog(@"songNamePath: %@", songNamePath);
if ([inSongData writeToFile:[documentsDirectory stringByAppendingPathComponent:songNamePath] atomically:YES])
{
// Success !
NSLog(@"Successfully saved the song into documents directory");
}
else
{
// Error !
NSLog(@"Error when Successfully saving song into documents directory");
}
}
-(NSData *) readSongDataFromDocsDirectory :(NSString *) filePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSData *readData = [NSData dataWithContentsOfFile:[documentsDirectory stringByAppendingPathComponent:filePath]];
return readData;
}
在此先感谢!
您好,感谢您的答复。你如何说存储音频文件?我的意思是,什么格式?你想让我把每首歌的NSData存储在文档目录中吗?因为我的歌曲网址来自服务器,我使用NSData * data = [NSData dataWithContentsOfURL:url];现在获取歌曲二进制文件。 – Getsy 2012-04-15 11:09:12
NSData有一个名为writeToFile的方法:atomically:它完全符合你想要做的。查看NSData的文档以了解如何使用它。 – 2012-04-15 11:17:30
嗨,我添加并存储到文件目录中大约70 mb的歌曲数据,但是当我尝试使用NSUserDefaults时,问题也是如此。 – Getsy 2012-04-15 16:24:52