1

我是 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
4

3 回答 3

1

with:

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

you've declared a global, mutable variable. it is not the same as an instance variable. this should not be used. furthermore, it's a definition -- this approach will result in linker errors.

with:

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

you're writing to a global, mutable variable. this is not thread safe. that's not to imply that an ivar is implicitly threadsafe, but it is generally more safe thatn global accesses because its access is restricted to the instance.

just declare it as an instance variable :)

于 2012-04-27T17:19:15.137 回答
0

只是我的2美分。它是一个全局变量,不太好。最好不要养成使用它的习惯。您很少会看到使用全局变量的代码。如果您学习了Objective-C 的所有基础知识,即协议、类别、扩展,您会发现您几乎不需要全局变量。

于 2012-04-27T17:25:53.403 回答
0

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

于 2012-04-27T17:09:50.923 回答