On May 12, 2012, at 08:27 , Andreas Grosam wrote:

> It seems, sending mutableBytes creates autoreleased objects (currently, 
> tested with ARC only).
> Anybody experienced this, too?
> 
> In code as below this may severely impact performance and tie up lots of 
> memory, which are apparently dependent on the size of the mutable data:
> 
> for (int i = 0; i < BigValue; ++i) {
>    NSMutableData* data = [[NSMutableData alloc] initWithCapacity:bigSize];
>    char* p = [data mutableBytes];
>    ...
> 
>    // data released by ARC
> }
> 
> I could alleviate the problem by wrapping around an autorelease pool:
> 
> 
> for (int i = 0; i < BigValue; ++i) 
> {
>    NSMutableData* data = [[NSMutableData alloc] initWithCapacity:bigSize];
>    char* p;
>    @autoreleasepool {
>       char* p = [data mutableBytes];
>     }
>    ...
> }

No, the pointer returned by 'mutableBytes' is an interior pointer. It *isn't* 
an object pointer. (Well, as an implementation detail, it may happen to point 
to an object's memory, but it often doesn't.)

As soon as the NSMutableData's lifetime ends -- when it reaches its dealloc -- 
the 'mutableBytes' pointer becomes instantly invalid.

Interestingly, this appears to mean that NSData/NSMutableData has become as 
dangerous in ARC as it is in GC. The compiler may shorten the lifetime of an 
object variable so that the interior pointer is catastrophically invalidated. 
This is documented in section 6.1 of the clang ARC spec:

        http://clang.llvm.org/docs/AutomaticReferenceCounting.html#optimization

but it also give an answer:

        NSMutableData* data __attribute__ ((objc_precise_lifetime)) = …

P.S. I think there's also another, better solution, but it involves adding a 
method to NSData/NSMutableData via a category:

        - (void*) interiorBytes __attribute__ ((objc_returns_inner_pointer)) {
                return self.bytes;
        }

        - (void*) mutableInteriorBytes __attribute__ 
((objc_returns_inner_pointer)) {
                return self.mutableBytes;
        }

and never using bytes/mutableBytes directly ever again. Perhaps one day 
bytes/mutableBytes will themselves be marked this way.


_______________________________________________

Cocoa-dev mailing list ([email protected])

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to