Possible Duplicate:
Objective-C - When to use 'self'
I am having problem understanding the use of self.
When i have to use it?
Can anyone explain to me?
Many Many Thanks.
Possible Duplicate:
Objective-C - When to use 'self'
I am having problem understanding the use of self.
When i have to use it?
Can anyone explain to me?
Many Many Thanks.
if you have instance variable and property with the same name, than if you call "[self myvar]", than you call a method "myvar", if you call just "myvar" than you ask instance variable directly. For properties better to call method (with self) because inside method "myvar" could be implemented some specific stuff (i.e. memory management, validation).
Example for better understanding:
@interface Possession : NSObject <NSCoding> {
NSArray *myArray;
}
@property (nonatomic, retain) NSArray *myArray;
- (void)someMethod;
@end
@implementation
@synthesize myArray; // this line adds two methods: "myArray" and "setMyArray:"
- (void)someMethod {
NSArray *firstArray = [NSArray arrayWithObject:@"test1"]; // autoreleased
self.myArray = firstArray; // it is ok. this new array will be
// retained in property's implementation of setMyArray
NSArray *secondArray = [NSArray arrayWithObject:@"test2"]; // autoreleased
myArray = secondArray; // memory leak here!!!! because previous value of myArray
// wasn't released and new value not retained. it means
// that when run loop finished you will lose your array
}
@end
self is used to access current class method,and variables, but it should be declared as properties, As far as my concern self means current class object.example if we have some method -(void)showData in one class and we like to call that method we write code as [self showData], and if there is some variable example string *name with proper defining properties and synthesize, we call that variable as self.name
As far as my knowledge self means current class object.For example if you want to call any method in the current class then you are using the [self somemethodname];
And also if you want to use the current class variables which are declared as properties then you can call those variables as self.somevariablename = @"ffs";