Re: Accessing pointer structure members inside block function
Re: Accessing pointer structure members inside block function
- Subject: Re: Accessing pointer structure members inside block function
- From: David Duncan <email@hidden>
- Date: Tue, 13 Dec 2016 09:37:43 -0800
> On Dec 13, 2016, at 8:20 AM, Andreas Falkenhahn <email@hidden> wrote:
>
> What is the recommended way of accessing pointer structure members inside
> a block function?
>
> Consider the following code:
>
> obj->width = 320;
> obj->height = 240;
>
> dispatch_async(dispatch_get_main_queue(), ^{
> printf("WIDTH: %d HEIGHT: %d\n", obj->width, obj->height);
> });
>
> obj->width = 640;
> obj->height = 480;
>
> I *always* want the block function to use the variable values at the
> time of the *declaration* of the block function, not at the time of
> its execution, i.e. obj->width and ->height should always be 320 and 240,
> respectively, in the block function above.
>
> What is the recommended way of doing this? Should I just assign them
> to temporary variables whose values are never changed, e.g.
>
> obj->width = 320;
> obj->height = 240;
>
> tmpwidth = obj->width;
> tmpheight = obj->height;
>
> dispatch_async(dispatch_get_main_queue(), ^{
> printf("WIDTH: %d HEIGHT: %d\n", tmpwidth, tmpheight);
> });
>
> obj->width = 640;
> obj->height = 480;
>
> Or is there a nicer solution? I'm asking because the temporary variable
> solution can become quite ugly if there are many variables…
You would need to assign them to some temporary. Keep in mind that you are capturing a pointer here and with all pointers, nothing stops the backing memory from changing. That said, assuming your struct is amenable, your solution doesn’t necessarily need to look that bad, such as:
typeof(*obj) copy = *obj;
dispatch_async(… ^{
print(…, copy.width, copy.height)
}
>
> --
> Best regards,
> Andreas Falkenhahn mailto:email@hidden
>
> _______________________________________________
>
> 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
--
David Duncan
_______________________________________________
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