0

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.

Community
  • 1
  • 1
JBL
  • 247
  • 3
  • 4
  • 13
  • here is s a nice article http://useyourloaf.com/blog/2011/2/8/understanding-your-objective-c-self.html – bilash.saha Nov 04 '11 at 07:44
  • 1
    self as a word indicating itself. This is just like 'this' keyword in c++ programming. It basically contains self reference. – Sudesh Kumar Nov 04 '11 at 07:44

3 Answers3

2

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
yas375
  • 3,940
  • 1
  • 24
  • 33
2

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

vijay gupta
  • 242
  • 1
  • 12
0

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";

Tendulkar
  • 5,550
  • 2
  • 27
  • 53