The easiest way to write NSData to a file

前端 未结 4 440
悲哀的现实
悲哀的现实 2020-12-05 01:36
NSData *data;
data = [self fillInSomeStrangeBytes];

My question is now how I can write this data on the easiest way to an file.

4条回答
  •  执念已碎
    2020-12-05 02:05

    Notice that writing NSData into a file is an IO operation that may block the main thread. Especially if the data object is large.

    Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:

    // Use GCD's background queue
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        // Generate the file path
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"yourfilename.dat"];
    
         // Save it into file system
        [data writeToFile:dataPath atomically:YES];
    });
    

提交回复
热议问题