Is this the right way?
// convert
const void *buffer = NULL;
size_t size = 0;
dispatch_data_t new_data_file = dispatch_data_create_map(data, &buffer, &size);
if(new_data_file){ /* to avoid warning really - since dispatch_data_create_map demands we care about the return arg */}
NSData *nsdata = [[NSData alloc] initWithBytes:buffer length:size];
// use the nsdata... code removed for general purpose
// clean up
[nsdata release];
free(buffer); // warning: passing const void * to parameter of type void *
It is working fine. My main concern is memory leaks. Leaking data buffers is not fun. So is the NSData, the buffer and the dispatch_data_t new_data_file all fine?
From what I can read on http://opensource.apple.com/source/libdispatch/libdispatch-187.7/dispatch/data.c it seems the buffer is DISPATCH_DATA_DESTRUCTOR_FREE. Does that mean it is my responsibility to free the buffer?
Since iOS 7 and macOS 10.9 (Foundation Release Notes) dispatch_data_t is an NSObject (NSObject <OS_dispatch_data>) in 64 bit apps.
dispatch_data_t can now be freely cast to NSData *, though not vice versa.
For the most part, your code is correct.
+initWithBytes:length: will copy the buffer sent in so, you don't have to worry about freeing the buffer after the data, you can safely free the data first.
According to the documentation, you do NOT free the data after you are done with it:
If you specify non-NULL values for buffer_ptr or size_ptr, the values returned in
those variables are valid only until you release the newly created dispatch data
object. You can use these values as a quick way to access the data of the new
data object.
You simply release the new_data_file variable (ARC will not do this for you).
Related
As the title suggests.
There is an old solution in Swift here. But I have hard time converting to Objective-C. Seems there is no Objective-C equivalent of UnsafeBufferPointer
Objective-C has unsafe pointers built right into the language, so the conversion simply becomes:
- (NSData *)bufferToNSData:(AVAudioPCMBuffer *)buffer {
return [[NSData alloc] initWithBytes:buffer.floatChannelData[0] length:buffer.frameLength * 4];
}
N.B. this assumes mono 32 bit float data in the buffer. More work needs to be done to serialize all supported AVAudioPCMBuffer formats to NSData.
I am an intermediate student in iOS development, I am trying to make a method that uploads an image to a server. I understand the server side scripting in PHP.
But when I am following a tutorial to upload an image in Xcode, I don't really grasp about NSData, NSObject, NSMutableData, NSString, it seems the tutorial doesn't really the fundamental aspect of NSData, NSMutableData, NSString...
If want to take beautiful display, I should learn about auto layout, collection view etc.
So, what kind of topic in iOS development that I should learn to really understand about these things step by step? It seems that I never learn specifically about these things. I don't know where to start.
The code to upload an image is like this:
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().UUIDString)"
}
}
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
Learning about objects you have described may mean many things. If you are after their capabilities then the documentation should be enough. But if you are more after what is under the hood and why we need these objects then I could only suggest you to look into some older language like C.
These objects NSData, NSMutableData, NSString are all data containers, buffers. But NSObject is just a base class from which all other objects inherit.
So a bit about NSData and NSMutableData:
In C when creating a raw buffer you use malloc which reserves a chunk in memory which you may use as you please. Once done you need to call free to release that memory or you will have a memory leak.
void *voidPointer = malloc(100); // Reserved 100 bytes of whatever data
int *intPointer = (int *)malloc(sizeof(int)*100); // Reserved enough bytes to fit 100 integers whatever their size may be
intPointer[13] = 1; // You may use these as normal array
free(voidPointer); // Free this memory
free(intPointer); // Free this memory
So NSData is basically a wrapper for that and does all of it for you. You may even access the raw pointer by calling bytes on NSData object.
Then the mutable version NSMutableData is just a subclass which has some additional functionality. You may actually append data. From what is under the hood appending data is not so simple. You need to allocate a new memory chunk, copy old data to it, copy new data and release the previous memory chunk.
void *currentData = malloc(100); // Assume we have some data
void *dataToAppend = malloc(100); // Another chunk of data we want to append
void *combinedData = malloc(200); // We need a larger buffer now
memcpy(combinedData, currentData, 100); // Copy first 100 bytes to new data
memcpy(combinedData+100, dataToAppend, 100); // Copy next 100 bytes to new data
free(currentData); // Free old data
free(dataToAppend); // Free old data
... use combinedData here ...
free(combinedData); // Remember to free combined data once done
These are all really simple methods but they may already be pain to write and it is easy to produce bugs doing so. So NSData or NSMutableData and even Data in Swift are all just data containers that make your developer life easier. And in Objective-C conversion from data to C buffers is as easy as it gets:
NSData *myData = [NSData dataWithBytes:myDataPointer length:myDataLength];
void *myRawPointer = [myData bytes];
The NSString is not really that different. In C we again have character pointer which is used as string so we write something like:
char *myText = "Some text";
These are a bit special, a convenience really. We could as well do:
char *myText = (char *)malloc(sizeof(char)*100);
And then fill the data character by character:
myText[0] = 'S';
myText[1] = 'o';
myText[2] = 'm';
...
myText[9] = 't';
myText[10] = '\0'; // We even need to set a null terminator at the end
and then we needed to free the memory again... But never mind the C strings, NSString is again a wrapper that is responsible to allocate the memory, assign data and do whatever you want with it. It has may methods you can use simply to make your life easier.
As to the code you posted it is a combination of the two. In your case your API accepts images as multipart form data requests which you may understand as a raw image file with a few texts added around it just to explain what the data contains. It is one of a generally used way but not the only one. You might as well just post the raw image data or you might even post a JSON containing a base64 string encoded data. Also as usually these texts are represented as an utf8 encoded data.
In the end it is a set of standards that are generally used so our computers may communicate between each other. Your image is most likely defined by a standard from png or jpg on how to present it with a string of bytes, your strings are defined by utf8 standard and your whole request body is defined by some HTTP standards (not even sure what part of it is that). And the objects you use and want to learn about are just some helpers for achieving your result. Understanding them in most cases is like understanding a screwdriver; you won't need to in most cases, but you do need to know they exist and you need to know when to use them.
The code itself you posted is relatively bad but should do its job. For a beginner it might be a bit confusing even. Probably a more logical pseudocode for this solution would be something like:
let imageData: Data // My image data
let headerString: String // Text I need to put before the image data
let footerString: String // Text I need to put after the image data
var dataToSend: Data = Data() // Generate data object
dataToSend.append(headerString.utf8Data) // Append header
dataToSend.append(imageData) // Append raw data
dataToSend.append(footerString.utf8Data) // Append footer
I hope this clears up a few things.
I am working on a Bluetooth based application and I am having problems when I try to send data from the iPhone to the other device.
I have no problem when I have to send just one value, using something like this:
- (void)sendData:(NSInteger)mel {
NSData *myData = [NSData dataWithBytes:&mel length:sizeof(mel)];
[self.myDevice writeValue:myData forCharacteristic:self.myCharacteristic type:CBCharacteristicWriteWithoutResponse];
}
But, for some characteristics I need send 2 or more values at the same time (for example in this case, variable mel and another one) but I haven’t been able yet to do it.
Does somebody know how to do this? Thanks in advance.
UPDATE 1
What I tried to send two values is
unsigned char bytes[] = {mel, interval};
NSMutableData *myData = [NSMutableData new];
[myData appendBytes:&bytes length:sizeof(bytes)];
[self.myDevice writeValue:myData forCharacteristic:self.myCharacteristic type:CBCharacteristicWriteWithoutResponse];
But this works like if the second value didn't exist
You can't use sizeof(bytes) to get the number of bytes in the array. It's simply going to return 4 since that is the size of a char *.
One options would be to use sizeof(mel) + sizeof(interval) instead of sizeof(bytes).
I have a C char *cArray and it's length, and I need to convert it to NSData
I did it with:
var data: NSData? = NSData(bytesNoCopy: cArray, length: Int(length))
And it's working. The problem is that this is causing some memory leak. I don't know why, but I can see it at the allocation instruments that it's malloc 64 bytes and not freeing it when the function finish or when I set it to null.
This code been called a lot, so I need it to be leaks-free. What can I do to prevent the leak?
Edit: this is the code
func on_data_recv_fn(buf: UnsafeMutablePointer<CChar>, length: CInt, user_data: UnsafeMutablePointer<Void>) -> CInt {
guard buf != nil else {
NSLog("on_data_recv_fn buf is nil")
return -1
}
//var data: NSData? = NSData(bytesNoCopy: buf, length: Int(length), freeWhenDone: true)
var data: NSData? = NSData(bytesNoCopy: buf, length: Int(length))
let succeededWriting = Int(PacketTunnelProvider.sendPackets(data!))
data = nil
return CInt(succeededWriting)
}
According to memory instruments, there is a leak here.
The sendPackets function does not holding the data so the problem isn't there.
Edit: attached an image from instruments.
Well, It's seems that if I use autoreleasepool everything is OK for some reason.
Memory management of types backed by Objective-C is a vast and interesting topic. See, for example, here:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html
You may also find this question useful:
Is it necessary to use autoreleasepool in a Swift program?
Also, I think there is a danger here if the buf passed to on_data_recv_fn was dynamically allocated by some C code, which later tries to free it. Another dangerous possibility: the function is a call-back implemented in Swift and called by C code. In this case the buf might be on the stack.
I haven't played with any of these scenarios, but according to NSData documentation, the bytesNoCopy initializer makes NSData take ownership of the memory and then de-allocate it; it assumes the memory was allocated using malloc(), so any memory that was not malloc'd should not be used to construct an NSData using this initializer. See https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/#//apple_ref/occ/instm/NSData/initWithBytesNoCopy:length:
There are other NSData initializers that make a copy of the buffer and can be safer in those cases.
I use this routine to do a binary read from file to memory, which worked fine until now... on iOS at least, in the simulator(...don't have the paid developer program(yet ;) ))
The numbers e.g. fileSize, bytesRead are OK, but it gives gibberish at the end...
I can't have overwritten memory, since I do the output right away...
Then I thought it could be an alignment boundary issue e.g. fileSize % 4 = det. gibberish.
But that would be strange behavior, the function gets a size and a count, the lib should calc a multiple byte read on the background, so that shouldn't cause the problem...
Here's the code I use:
uint8_t *readFileToMemory(FILE *fp)
{
fseek(fp, 0, SEEK_END);
long fileSize = ftell(fp);
rewind(fp);
//
printf("fileSize %lu bytes\n",fileSize);
//
uint8_t *fileData = NULL;
//
fileData = (uint8_t *)requestMemory(fileData, (MEM_TYPE_MEMSIZE)fileSize, BF_MEM_ZERO_NO, "readFileToMemory()");
fread(fileData, 1, (size_t)fileSize, fp);
//
long sizeRead = fread(fileData, 1, (size_t)fileSize, fp);
printf("sizeRead %lu bytes\n",sizeRead);
//
fclose(fp);
//
printf("+\n+\nfileData:\n%s+\n+\n",fileData);
//
return fileData;
}
The reason why I post this question is "WHY the gibberish?" on iOS-sim, I do have a simple workaround btw...
Niels
I am here now, so I might as well provide an answer for closure ;)
I forgot to put an '\0' at the end of the binary file before passing it along as (c/glsl NULL-terminated)string... Oops :)
I thank borrrden for his remarks on the Apple libs binary-read, which I still need to look into... (time time time)
Niels