I am using the following code to convert nsdata to bytearray. It works fine in simulator. On device, it allocates memory like crazy to 600 MB [on the 'addobject' line inside the loop] and crashes. The file size I am reading is 30 MB. The error I see in output windows is "memory issue". The file is a "zip" file
NSData *data = [[NSData alloc] initWithContentsOfFile:file];
const unsigned char *bytes = [data bytes];
NSUInteger length = [data length];
NSMutableArray *byteArray = [NSMutableArray array];
for (NSUInteger i = 0; i < length; i++) {
@autoreleasepool {
[byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]]; }
}
I am using this bytearray inside a NSDictionary and do a "dataWithJSONObject" on the dictionary to post the json to a REST web service.
For a more memory efficient way to convert NSData to byte array, see How to convert NSData to byte array in iPhone?
If your goal is ultimately to post the binary data to a web service in JSON, try the following:
For the second approach, I can think of two ways to do this:
Here is an example for the scenario of sending an image , but any file type will work so long as you can load it into an NSData object.
Or, something like this should work
NSData *data = [NSData dataWithContentsOfFile:file]; NSURL *url = [NSURL URLWithString:@"your_url_here"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"PUT"]; NSDictionary *headers = @{@"Content-Type": @"application/octet-stream"}; [request setAllHTTPHeaderFields:headers]; [request setHTTPBody:data] // Use an URLSession object task to execute the request
Lastly, if the data can be compressed on the client before encoding and sending, that would be even better!
I hope you find this helpful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.