iOS程序员iOS程序猿

OC — self指针

2017-09-24  本文已影响31人  Cy_Star

1、self 表示当前对象
2、是在执行该函数,self 就表示谁。

如下:
[xiaomi setName:@"小米"];   // 这里 self 表示 xiaomi 对象
[xiaoli setName:@"小李"];
-(void) setName: (NSString *)newName
{
  那么 self 在使用该类方法,self 就表示类的本身
    //self 其实就是调用该函数的对象  [对象 setName:@"小米"];  
      换个对象变成 xiaoli在调用这个函数  [对象 setName:@"小李"]; 那么 self 就表示 xiaoli ;总的来说是谁在调用这个函数,self 就表示谁。
    //
     [self setNewName: newName];

}
-(void) setNewName: (NSString *)newName
{
      _name = newName;
}

3、self 如果在类的方法里面,表示类的本身;如果是在对象里面,表示对象本身。

如下:
有一个Dog类

1、
类方法调用:[类 类方法];
int age = [Dog maxAge];
+ (int) maxAge
{
    // 上面所说的 self 是一个当前的本对象(是在 -(){方法里面} ) 
   // 在 + (静态方法){类方法} self 就表示本类
    NSLog(@"%@",self);
    return 150;
}    

------------------------------------------------------------

2、
Dog * dog = [Dog xiaoGou]; //这里 self 表示 Dog 类

+ (id) xiaoGou {
       id obj = [[self alloc] init];  等于  id obj = [[Dog alloc] init]; 
      // 前者写法提高通用性,这时候 self 就表示当前的类
      //另一种写法
       id obj = [[[self  class] alloc] init];
      //那么这个class 就是 让强迫返回 self 这个类的类,就是返回当前类的类
        return obj;
  }
  
  ------------------------------------------------------------------------------------------------------------

3、
+ (id) dogName: (NSString *)newName withAge: (int) newAge {
    // 这里的 self 也是表示当前的这个 类
      id obj = [[self alloc] initWithName: newName withAge: newAge ];
    return obj;
}

-(id) initWithName: newName withAge: newAge {
    self = [super init]; //这里super 表示 self的父对象,面向对象中有继承,所以super就是基类对象
  if (self) {
        [self setName: newName];
        [self setAge: newAge];
  }
return self;

}
4、self 表示谁,在运行时是由编译器来决定的

上一篇下一篇

猜你喜欢

热点阅读