What is happening if code is wrapped in curly braces within a function?
I'm new to Objective C and have noticed in code I've read that sometimes a block of code will be wrapped in curly braces inside of a function.
What does this do?
For example ...
- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions {
// Load config, available via macro CONFIG
{
NSString *path = [[NSBundle mainBundle] pathForResource: @"config" ofType: @"plist"];
NSData *data = [[NSData alloc] initWithContentsOfFile: path];
self.config = [NSPropertyListSerialization propertyListWithData: data
options: NSPropertyListImmutable
format: nil
error: nil]开发者_如何转开发;
[data release];
}
// snip
}
That's called "scope"...
Variables declared inside the braces only exists inside the braces.
Imagine the following:
int main( void )
{
int my_var = 3;
{
int my_var = 5;
printf( "my_var=%d\n", my_var );
}
printf( "my_var=%d\n", my_var );
exit( 0 );
}
This will print:
my_var=5
my_var=3
It's just a way of limiting the scope of the variables declared in the block. In your example path and data will not be visible outside of the curly braces.
精彩评论