Question

I'm little confuse because in some tutorials is just

in h

@property (readwrite,nonatomic) NSUInteger DirectProp;

in m

@synthesize DirectProp;

But in other is like this

in h

@interface MyClass : CCNode {
    NSUInteger throuVarProp;

}
@property (readwrite,nonatomic) NSUInteger ThrouVarProp;

in m

@synthesize ThrouVarProp = throuVarProp;

Which way is the right way?

Was it helpful?

Solution 2

With a single argument:

@synthesize directProp;

The synthesized getter/setter methods are called the same as the instance variable used to store the value. This can get confusing. For example:

self.directProp = YES;

[self setDirectProp:YES];

directProp = YES;

Are all valid.

With the additional = ivar, you are able to name the instance variable (the convention being to use a leading underscore), which is a good idea, so you don't get confused:

@synthesize directProp = _directProp;


self.directProp = YES;

[self setDirectProp:YES];

_directProp = YES;

As also mentioned, with newer runtimes you don't need to declare the instance variable before use, which is also a bad idea and seems to be there to promote laziness. You will regret using this feature some day...

OTHER TIPS

Both are correct...

The difference is in older and newer style of writing.

In latest versions of Xcode you will see even synthesize is not required and it will take automatically as _yourIvarName

They are both right.

With:

@interface MyClass : CCNode {
    NSUInteger throuVarProp;

}

You are saying to the compiler that that object has an instance variable of NSUInteger kind. This if formally correct, but now this code is auto generated by Xcode and the compiler when you use a @property.

@syntesize, used in the implementation, creates the getter and setters: special instance methods used to access your instance variable from "outside".

In the last XCode (AFAIK from 4.4) even the @syntesize is auto generated, in the format

@syntesize var = _var;

Newer runtimes don't require you to define the iVar. In fact, they even auto-synthesize the iVar for you.

// .h
@property (…) Type name;

This will automatically synthesize the property as if you had written:

// .m
@synthesize name = _name;

Thus you're even able to access the underlying variable, which I would not recommend though because I consider it an underlying implementation detail.

Note that if you override the getter the auto-synthesis will no longer happen:

// .m
@synthesize lazyProperty = _lazyProperty;
- (NSString *)lazyProperty {
    if (!_lazyProperty)
        _lazyProperty = @"Foobar";

    return _lazyProperty;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top