0

You can declare a variable like this.

Case1:

@interface MyClass : NSObject
{
    NSString *str;
}

@end

Also, if you want to set its property, you can do

Case2:

@interface MyClass : NSObject
{
    NSString *str;
}
@property (nonatomic, strong) NSString *str;

@end

And in the .m,

@synthesize str;

My understanding with the difference between Case 1 and Case 2 is that synthesized and propertied variables in Case 2 can be accessed from another class when this another class instantiates this class.

What are other differences between Case 1 and 2? Say when these variables are just used only in its .m file. The fact that you are setting 'str' properties probably makes a difference, but how? If you don't set property, how are they going to be released with ARC?

1 Answer 1

1

The differences are fairly confusing in this case because of the way it is set up.

Also it is using what is now old practises.

The new suggested way of doing this (suggested by Apple) is to do this...

MyClass.h

@interface MyClass : NSObject

@property (nonatomic, strong) NSString *str;

@end

MyClass.m

#import "MyClass.h"

@implementation MyClass

@end

You no longer need the @synthesize as Xcode (since 4.5) will auto generate these for you.

Doing this sets up the property called str and an iVar called _str.

You now no longer need to worry about defining multiple ivars and properties etc... Just use the property and that's it done.

An example setter method for the property str would look like this...

- (void)setStr:(NSString*)str
{
    _str = str;
}
Sign up to request clarification or add additional context in comments.

14 Comments

you still need @synthesize if you want to use it without going self.str
So for all instance variables, I better declare its property? I shouldn't declare any instance variable between the squiggly brackets?
@Fonix no you don't. The synthesize is now "assumed" by the compiler and an ivar with an underscore is set up. Rocky, I only ever use properties now. There is now "correct" way. It is more personal preference. But I find properties are easier to manage in ARC and also to control the way they are retained etc...
Also, with a property set up this way you can still access the synthesized ivar _str. I'll add a setter method as an example.
You may think it is ugly but by synthesizing an ivar without an underscore you are just creating confusion (evident in these comments) between the property and the ivar. Besides the underscore is Apple's suggested best practise. No offence, but I'll stick with what Apple suggests over what you suggest. :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.