1

我正在从服务器下载几首小型歌曲并将(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;
}

提前致谢!

4

1 回答 1

0

最好将这些音频文件存储在文档目录中,因为这将减小应用程序的大小,NSUserDefaults 通常用于存储在特定于应用程序的小设置中,例如应用程序特定用户的首选项和所有设置。希望这会有所帮助。. :)

无论您存储在 NSUserDefaults 中的任何内容都会增加应用程序的大小,因为该对象在应用程序运行时始终处于活动状态......

于 2012-04-15T11:01:31.203 回答