R – Does NSString stringWithCString: length: retain the byte array I pass in

cocoamemory-managementnsstring

I'm working with AsyncSocket where the the AsyncSocket object calls a delegate method below whenever it receives data from remote end:

- (void)onSocket:(AsyncSocket*)socket didReadData:(NSData*)data withTag:(long)tag;

Now, within this method, I pass the NSData object into the following command to get a NSString representation of the data received:

NSString *body = [NSString stringWithCString:[data bytes] length:[data length];

Does NSString stringWithCString: length: retain the byte array I pass in? Do I need to retain the NSData *data? Do I need to be releasing NSString *body at the end?

Thanks. I want to get memory management right in terms of delegates methods…

Best Answer

Does NSString stringWithCString: length: retain the byte array I pass in?

It's not possible to retain a byte array. Only objects can be retained.

Do I need to retain the NSData *data?

No. Because there's no way for the string to retain the data (which it doesn't know about) or its contents, the string will copy the bytes. (Think about what you would do if you were implementing this method: This is it.)

Let's change cases and look at what you would do if you were passing the data object in, instead of the bytes.

If the string does retain the data, then you don't need to worry about the data dying out from under the string, because the string is retaining it. If it doesn't retain it, the string either made its own copy or isn't holding on your data at all.

So other objects' retentions don't matter. Don't worry about them. Worry only about who owns what, and retain or not accordingly.

Do I need to be releasing NSString *body at the end?

Well, you didn't retain it, you didn't alloc it, and you didn't copy it. Therefore, you don't own it. So, no.

If you do want to take ownership of the object, you'd retain it or make (and then own) your own copy. Then you would release it.

Related Topic