What is the difference in defining a variable in .h file's interface() method alone without synthesizing it?

StackOverflow https://stackoverflow.com/questions/4643692

문제

I define a variable in .h file's interface method like this...

@interface ......{
  int a;
}

Then i use it in .m file, it works fine....

Also i modified the code as

@interface ......{
  int a;
}
@property(nonatomic) int a;

in .h file, and in .m file i set the int value as

@synthesize a;

Now also it works fine...

What is the different between both cases?

도움이 되었습니까?

해결책

By declaring your 'a' property you are allowing for the int to be stored in your class and you can access it from within your class - but only within your class. If you want it to be a property that is accessible by other objects (a public property) then you need getter and setter methods.

By declaring it as a @property in your .h and using @synthesize in your .m, you are automatically creating two methods:

[myObject a]; // your getter
[myObject setA:50]; // your setter

One thing to keep in mind here is that it is often a very good idea to use sythesised properties even within your class because they will take care of your memory management. For example, when you flag the @property as retain:

objectProperty = anObject; // just accessing locally, no memory management
self.objectProperty = anObject; // [anObject retain] will be called
self.objectProperty = nil; // [anObject release] will be called

다른 팁

In first case you use field, with direct access to it. In second case you are defining Objective C property, with accessors.

If you define and synthesize a property, then you can also access the value using int value = self.a; self.a = newValue;. This also makes the variable accessable to other objects. Without the property, you cannot use the self. to get to the variable and there is no automatic way for other objects to get to it.

When you define and synthesize a property you tell compiler to generate both ivar and accessor methods (-(int)a; and -(void)setA:(int)a_;) for it. Those methods can be called explicitely or implicitely using dot syntax:

self.a = num; // [self setA:num] gets called 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top