Amrmsmb
Amrmsmb

Reputation: 11416

How to initialise private member variable

In the below code I want to declare a private instance variable and initialise it to zero But when I try to initialise it to zero I receive irrelevant error “; comma expected at the end of the statement”

As an attempt to solve the issue, I tried to find out to which value this variable is initialised:

-(void) startRecursion: (UIView *) uiviews {
    if (!uiviews) {
    return;
    }
    NSLog(@"numOfMethodCalls: %d", ++self->numOfMethodCalls);
    NSUInteger *countOfSubViews = [uiviews.subviews count];
}

However, the log printed :

2019-11-10 14:08:25.711847+0100 UIEnhancement_00[10065:383388] numOfMethodCalls: 8

Please let me know how to solve this issue

code:

@interface UIEnhancements : NSObject {
 NSUInteger *numOfMethodCalls;
}

+(id) initSelf;

Upvotes: 0

Views: 48

Answers (1)

CRD
CRD

Reputation: 53010

Instance variables are automatically initialised to zero in Objective-C.

Your code is printing 8 as you declared your variable as NSUInteger * – a pointer (*) to an NSUInteger. Now on a 64-bit platform an NSUInteger is 8 bytes long.

(Objective-)C defines the operator ++ on a pointer to increment it by the size of whatever type it points at. So numOfMethodCalls was initialised to 0 automatically and then the ++ added 8 to it.

Instance variables are best private, as you state you intended, but you have declared it publicly in the @interface. The best way is to declare it in the implementation:

@implementation UIEnhancements
{
   NSUInteger numOfMethodCalls;
}

...

@end

Lastly though you don't show an implementation you declare:

+(id) initSelf;

in your interface. Only methods which are initialisation methods should start with init, they are instance methods, and in modern Objective-C are normally declared to return instancetype (rather than id) which improves compile-time type checks. In summary:

- (instancetype) initSelf;

though if it is your only initialisation method you should call it simply init.

HTH

Upvotes: 1

Related Questions