我正在从服务器下载几个小型歌曲并将(NSData)存储到NSUserDefaults中,以便我可以在需要时使用它来直接在设备上缓存和播放,而不是从服务器下载和播放。 问题是,如果我在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;
}
提前致谢!
答案 0 :(得分:0)
更好地将这些音频文件存储在文档目录中,因为这会减小应用程序的大小,NSUserDefaults通常用于存储在特定于应用程序的小设置中,例如首选项和应用程序的特定用户的所有内容。希望这会有所帮助。 。 :)
无论你存储在NSUserDefaults中的是什么,都会增加应用程序的大小,因为当应用程序运行时,此对象始终处于活动状态...