Solved

C memcpy() in Objective-C method

Posted on 2010-11-30
2
2,606 Views
Last Modified: 2013-11-25
Hi, I'm writing a method in objective-c who's aim it is, is to prefix some data with a 4-byte length of the following data.  However, my C is incredibly rusty and after running allocations with and without the following method, I'm led to believe it leaks (I'm not surprised).

Could anyone help me out.
 
-(NSData *) addPrefixMessageFramingToData:(NSData *) msgData
{
	NSInteger length = [msgData length]; 
	unsigned char *lengthPrefix = (unsigned char*)&length;
	
	unsigned char lengthPrefixBuffer[4] = { 0, 0, 0, 0 };
	memcpy(lengthPrefixBuffer, (unsigned char *)lengthPrefix, 4);
	
	NSMutableData *newSend = [[NSMutableData alloc] initWithBytes:lengthPrefixBuffer length:4];
	[newSend appendData:msgData];
	
	return [newSend autorelease];
}

Open in new window

0
Comment
Question by:Type25
2 Comments
 
LVL 24

Accepted Solution

by:
fridom earned 500 total points
ID: 34246565
I'm afraid this mix between Objects and "primitive" data types won't work.
I do not dare to speculate what this does:
NSInteger length = [msgData length];
      unsigned char *lengthPrefix = (unsigned char*)&length;

Why don't you take the lenght at the 4 bytes to it and fill the Mutable Data then?

0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question