Curly Braces in Objective-c

两盒软妹~` 提交于 2019-12-20 05:39:18

问题


Note: My question is based after checking this and the answers to it.

In some bigger methods, there are pieces of code that you only want to be alive for a certain period of time. An example:

1) I have a big method that sets my UI: UILabel's size, colour, positioning, UIView's gesture recognisers, etc. Knowing the above, does it makes sense to do something like this:

- (void)setUI
{
    //setting other UI elements
    {
        // Add the Swipe Gesture to the swipeUpView
        UISwipeGestureRecognizer *swipeGestureUp = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(animeViewWithSwipeGesture)];

        swipeGestureUp.direction = UISwipeGestureRecognizerDirectionUp;
        [_swipeUpView addGestureRecognizer:swipeGestureUp];
    }

    // setting other UI elements
}
  • Based on the above example, is this a valid way of lowering the memory footprint of an application?
  • Is there any relation with @autoreleasepool{}?

回答1:


Based on the above example, is this a valid way of lowering the memory footprint of an application?

No. They're not even related. Neither are they related to @autoreleasepool - this usage of curly braces is the plain C way of opening a new scope.




回答2:


It's just plain C syntax. You use it to open a new scope as others mentioned. What this means (this is C feature) that you can use same names for stack variables again, as they are in different scope. Also, variables you declare inside that scope will not be accessible by outside scope.

There is no relation to memory footprint, only about code organization.




回答3:


What curly braces do is just to define a new scope, so you can define new variables with the same name than other outer scope variables.

The @autoreleasepool{} block is quiet similar, but also declares an autorelease pool at the beginning and drains it at the end, so it may be better from a memory footprint point of view because all the autoreleased objects declared there will be released when exiting that scope.



来源:https://stackoverflow.com/questions/12507738/curly-braces-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!