Objective-C编码风格(相当语义)

时间:2012-04-27 17:01:11

标签: objective-c

我是Cocoa的新手,我想确保我使用的样式和代码符合我的目的。

具体在标题中(标记为a)),将变量设置在@interface之外会产生什么影响?

其次,在实例中使用变量(在b)处)而不在类声明中注册它会产生什么影响?

标题文件:

    #import <UIKit/UIKit.h>

    ///////////// a) Is this good use?
    int myint; 
    /////////////        

    @interface InstancecheckViewController : UIViewController
    - (IBAction)plusone:(id)sender;
    @property (weak, nonatomic) IBOutlet UILabel *counting;
    @end

实现:

    #import "InstancecheckViewController.h"
    @interface InstancecheckViewController ()
    @end
    @implementation InstancecheckViewController
    @synthesize counting;

    ///////////////////// b) is this good use?
    - (void)resetit {
        myint = 0;   
    } 
    /////////////////////

    - (IBAction)plusone:(id)sender {
        myint ++;
        if (myint >10){
            [self resetit];
        }
        NSString* myNewString = [NSString stringWithFormat:@"%d", myint];
        counting.text = myNewString;
    }
    @end

修改
感谢大家的意见。 我想我现在已经正确地重新定义了实例和.h

中的整数
    @interface instancecheckViewController : UIViewController
    {
    @private
    int myint;
    }
    - (IBAction)plusone:(id)sender;
    - (void)resetIt;
    @end

3 个答案:

答案 0 :(得分:1)

使用:

///////////// a) Is this good use?
int myint; 
/////////////        

你已经宣布了一个全局的,可变的变量。它与实例变量不同。这不应该使用。此外,它是定义 - 这种方法会导致链接器错误。

使用:

///////////////////// b) is this good use?
- (void)resetit {
    myint = 0;   
} 
/////////////////////

你正在写一个全局的,可变的变量。这不是线程安全的。这并不意味着ivar是隐式线程安全的,但是全局访问通常更安全,因为它的访问仅限于实例。

将其声明为实例变量:)

答案 1 :(得分:0)

通过这种方式,您将声明一个跨实例共享的全局变量。因此,如果您从类的实例更改它,它将影响所有其他实例。我不确定你是否想要这个;如果您不需要明确上述行为,我建议您使用实例变量。

答案 2 :(得分:0)

只需2美分。这是一个全局变量并不是很好。最好不要养成使用它的习惯。您很少会看到使用全局变量的代码。如果您了解Objective-C的所有基础知识,即协议,类别,扩展,您将看到您无论如何都很少需要全局变量。

相关问题