在方法中有大括号是什么意思?

时间:2013-12-27 16:30:32

标签: ios objective-c methods brackets

我正在Github上阅读一个代码示例,我看到了一些我会理解它是如何工作的东西。

代码类似于:

- (void)viewDidLoad
{
    [super viewDidLoad];

    {
        self.formatter = [[NSDateFormatter alloc] init];
        [self.formatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"yyyyMMMd" options:0 locale:[NSLocale currentLocale]]];
    }

}
这是什么意思?它是否与代码部分的异步执行有关? 有人开导我吗?

3 个答案:

答案 0 :(得分:4)

你说括号。你是在谈论花括号吗? “{”和“}”。

大括号定义了一个局部范围。它可以简单地用于代码可读性,或者也可以用它来限制局部变量的范围:

- (void)viewDidLoad
{
  [super viewDidLoad];
  {
    //local variables inside these braces are only defined inside this set of braces
    NSString *scratchString;
    int count = 1;
    scratchString = @"foo";
  }

  {
    //The string scratchString below is a different local variable than
    //The one defined above.
    NSString *scratchString;
    int count = 5;
    scratchString = @"bar";
  }
}

答案 1 :(得分:0)

[]是客观C通过消息进行通信的方式。如果它是一个函数,它只会慢一点。

答案 2 :(得分:0)

这些括号是Objective C方法调用语法。

实例方法调用的基本语法是

[target_object message_name];

如果消息采用参数:

[target_object message_name: parameter];

我建议读一本关于Objective C语言的书。