黑马程序员技术交流社区

标题: self.age=age为什么是死循环? [打印本页]

作者: 杨勇    时间: 2014-4-27 13:08
标题: self.age=age为什么是死循环?
本帖最后由 杨勇 于 2014-4-30 08:43 编辑

@interface Person : NSObject
{
    int _age;
}
- (void)setAge:(int)age;
- (int)age;
@ end

@implementation Person
- (void)setAge:(int)age
{
    self.age=age;//    1
}
- (int)age
{
   return self.age;//    2
}


请问1和2两处为什么会是死循环,不是简单的赋值和取值么?谢谢。
@end

作者: gmadong@163.com    时间: 2014-4-27 13:20
- (void)setAgeint:age
{
    self.age=age;//    因为self.age是调用的setAgeint:方法也就是自己调自己就死循环了
}

作者: 执着的土豆    时间: 2014-4-27 13:40
gmadong@163.com 发表于 2014-4-27 13:20
- (void)setAgeint:age
{
    self.age=age;//    因为self.age是调用的setAgeint:方法也就是自己调自己 ...

他说得对!
作者: 执着的土豆    时间: 2014-4-27 13:43
一楼说的对,我试了一下,给你分析得代码你参考一下。
  1. #import <Foundation/Foundation.h>
  2. @interface Penson : NSObject
  3. {
  4.     int _age;
  5. }
  6. - (void)setAge:(int)age;
  7. - (int)age;
  8. @end

  9. @implementation Penson
  10. - (void)setAge:(int)age
  11. {
  12.     NSLog (@"11");
  13.     self.age=age;//    1
  14.     NSLog(@"22");//执行会发现不会输出22,只会不断输出11,说明22这句代码永远不会执行,也就是说,在上句代码中他会调用当前方法,再输出11,到了第二句,再调用当前方法,再打印11。这就是死循环了
  15. }
  16. - (int)age
  17. {
  18.     return self.age;//    2
  19. }
  20. @end

  21. int main()
  22. {
  23.    
  24.    
  25.     Penson *p=[Penson new];
  26.     [p setAge:10 ];
  27.    
  28.      return 0;
  29. }
复制代码

作者: 2014571245    时间: 2014-4-27 17:01
同学,MJ老师的视频里貌似讲过哦,关键字selfde 用法,嘻嘻
作者: gaoxinglei123    时间: 2014-4-27 20:45
楼主。你申请的成员变量是int _age。你的self.age其实是oc中的点语法。本质是调用了本类的setAge方法。。你在setAge中调用setAge。。。当然会死循环了。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2