Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private variables in the @implementation

Is it a good practice to declare some private element in the .m, instead of doing a @property on the .h?

And, if it's OK, are these element considered as weak?

Example: (in the top of .m)

   @implementation ParticipantMaterials{
        UIImageView *imgBackground;
        UILabel *lblTitle;
        UITableView *tvTableContent;
        NSMutableDictionary *tblElements;
    }
like image 267
Franck Avatar asked Nov 29 '22 01:11

Franck


2 Answers

When declaring variables in the @implementation region, you are declaring instance variables, not properties. You do not @synthesize ivars. If you want to declare private properties hidden from the public .h file, you can create them like so:

@interface ParticipantMaterials ()

@property (nonatomic) NSUInteger uintProp;
@property (nonatomic, copy) NSString* strProp;

@end

This is called a class extension.

Instance variables are considered strong by default, unless you specify the __weak type modifier.

like image 94
Léo Natan Avatar answered Dec 09 '22 16:12

Léo Natan


If you want to declare private variables, any of these declarations will do:

@interface Animal : NSObject {
    @private
    NSObject *iPrivate;
}
@end


@interface Animal(){
    @public
    NSString *iPrivate2;
}
@property (nonatomic,strong) NSObject *iPrivate3;
@end

@implementation Animal {
    @public
    NSString *iPrivate4;
}
@end

I added the @public to point out that it makes no difference. All of those variables are equally private, and if you attempt to set them from a subclass or a different class, it will result in a compiler error: undeclared identifier or, in the first case compiler error: variable is private.

All object variables under ARC are strong by default, so you can omit strong from the @property if you like.

Variables in Objective-C are not 100% private. You can get/set them from anywhere using the runtime functions class_getInstanceVariable and object_getIvar.

like image 24
Jano Avatar answered Dec 09 '22 16:12

Jano