What does inout CGPoint * mean as a parameter?
Asked Answered
I

1

7

In the UIScrollView delegate methods, there's:

scrollViewWillEndDragging:withVelocity:targetContentOffset:

and the last parameter is:

(inout CGPoint *)targetContentOffset

I'm curious as to what the inout means and why CGPoint is a pointer. I tried printing targetContentOffset to the console, but I'm not sure how to do so as well. Any help is appreciated!

Imp answered 17/9, 2013 at 17:41 Comment(1)
For printing, use *targetContentOffset to fetch the thing it points to, or targetContentOffset->x (-> instead of .) to access members of a struct via pointer; I'm sure someone will give a properly substantial answer as to the whys.Isthmus
M
24

It means the parameter is used to send data in but also to get data out.

Let's see an example implementation:

- (void)increment:(inout NSUInteger*)number {
    *number = *number + 1;
}


NSUInteger someNumber = 10;
[self increment:&someNumber];
NSLog(@"Number: %u", someNumber); //prints 11

This pattern is often used with C structures, e.g CGPoint because they are passed by value (copied).

Also note that inout is not absolutely required there but it helps the compiler to understand the meaning of your code and do better job when optimizing.

There are also separate in and out annonations but as far as I know there are no compiler warnings when you misuse them and it doesn't seem Apple is using them any more.

Musgrave answered 17/9, 2013 at 17:44 Comment(2)
Do you happen to know where in/out/inout etc are documented? They are still present in the preprocessed output, so it must be compiler keywords and not macros, but I could not find an official reference.Spin
@MartinR Me neither. The were probably used only for distributed objects, see #5610064Musgrave

© 2022 - 2024 — McMap. All rights reserved.