Declaring instance variables in iOS - Objective-C

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-30 11:48:10

问题


Ok, I've read a lot around these days about this topic and I alwyas get confused because the answers is different every search I make.

I need to know the best way to declare instance variables in iOS. So far I know I should only declare them inside .m file and leave .h clean. But I can't do it: the compiler gives me compilation erros.

Here is some code from .m only.

@interface UIDesign ()

// .m file
{
    NSString *test2 = @"test2";
}

@property (nonatomic, assign) int privateInt;

@end

@implementation UIDesign
{
    NSString *test1 = @"test1";
}

Both strings are declared incorrectly and I don't know why. The compiler says: expected ';' at end of declaration list.

So the question is: how can I declare instance variables? I will only need them inside the class.


回答1:


You cannot initialize instance variables. They are all initialized to nil or zeroes. So compiler expect a semicolon when you are writing an equal sign.

You can initialize them in init method.




回答2:


You are attempting to add an instance variable to a class extension or category which is unsupported. [EDIT 2013-05-12 06-11-08: ivars in class extension are supported, but not in categories.] As an alternative:

@interface UIDesign : NSObject
@end

@interface UIDesign ()

@property (nonatomic, assign) int privateInt;
@end

@implementation UIDesign

@synthesize privateInt = _privateInt;

- (void)someMethod {
    self.privateInt = 42;
}

@end

On the other hand, if you just want to declare an instance variable inside the implementation, just do it there:

@implementation UIDesign {
    int _privateInt;
}

@end

EDIT: just noticed that you're also attempting to initialize instance variables in the declaration which is also unsupported. So:

@interface UIDesign : NSObject
@end

@implementation UIDesign {
    NSString *_test;
}

- (id)init {
    self = [super init];
    if( !self ) return nil;

    _test = @"Foo";

    return self;
}

@end


来源:https://stackoverflow.com/questions/16506357/declaring-instance-variables-in-ios-objective-c

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