Re: Accessing buffers in NSData/NSMutableData under garbage collection
Re: Accessing buffers in NSData/NSMutableData under garbage collection
- Subject: Re: Accessing buffers in NSData/NSMutableData under garbage collection
- From: Mika Ryynänen <email@hidden>
- Date: Tue, 19 Feb 2008 08:19:29 +0200
I have to confess that, in my tiny simplified test cases, I can't
replicate a crash by accessing a pointer to the 'bytes' in an NSData
object:
-(IBAction)danglePointer:(id)sender {
int size = 1e6;
NSMutableData *testData = [NSMutableData
dataWithLength:sizeof(float)*size];
float *testPointer = (float*)[testData mutableBytes];
[[NSGarbageCollector defaultCollector] collectExhaustively]; //
Thought this would reclaim testData, but seems not
NSLog(@"Sleeping...");
sleep(10); // Give time for collector thread to do its thing -
probably not needed?
NSLog(@"Done.");
BOOL flag = YES;
if (flag) {
testPointer[0] = 3;
NSLog(@"testPointer = %f",testPointer[0]);
}
// The above code fragment does not seem to crash, ever. Why not?
This code is safe because you have stored a pointer to the
NSMutableData (in NSMutableData *testData), which prevents the object
from being garbage collected. Consider if you would have the lines:
NSMutableData *testData = [NSMutableData
dataWithLength:sizeof(float)*size];
float *testPointer = (float*)[testData mutableBytes];
changed to:
float *testPointer = (float*)[[NSMutableData
dataWithLength:sizeof(float)*size] mutableBytes];
Here you would start having crashes again, because the garbage
collector would not be able to see that the NSMutableData object is
still in use. In your example, the testData pointer keeps the
NSMutableData valid until the pointer is set to nil or it goes out of
scope when the function ends.
So, to me it seems that your test case is doing the right thing. If
you were targetting Leopard only, it would probably easier to use
NSAllocateCollectable as Adam demonstrated earlier in this thread.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden