What are @property and @synthesize used for in Obj

2020-04-19 19:36发布

问题:

What is the use of @property and @synthesize? Can you explain with an example please?

回答1:

Really short answer: They create accessors for the ivars.

There are some examples on wikipedia. Look at those.



回答2:

From the apple developer library:

You can think of a property declaration as being equivalent to declaring two accessor methods. Thus

@property float value;

is equivalent to:

- (float)value;

- (void)setValue:(float)newValue;

And by using @synthesize, the compiler creates accessor methods for you (see more here)



回答3:

// Sample for @property and @sythesize //

@interface ClassA

  NSString *str; 

@end

@implementation ClassA

@end

The Main Function main()

//make sure you #import ClassA

ClassA *obj=[[ClassA alloc]init];

obj.str=@"XYZ"; // That time it will give the error that we don't have the getter or setter method. To use string like this we use @property and @sythesize


标签: objective-c