[关闭]
@fiy-fish 2015-05-18T16:40:13.000000Z 字数 811 阅读 1040

构造方法

Objective-c


  1. // Cat.h
  2. // 构造方法
  3. //
  4. // Created by Aaron on 15/5/18.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. @interface Cat : NSObject
  9. {
  10. int _color;
  11. }
  12. -(void)printMe;
  13. @end
  1. // Cat.m
  2. // 构造方法
  3. //
  4. // Created by Aaron on 15/5/18.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import "Cat.h"
  8. @implementation Cat
  9. //void *
  10. //malloc
  11. //泛型指针
  12. //id 泛型的对象指针
  13. -(id)init
  14. {
  15. //self 是一个指针
  16. //self就是消息的接收者
  17. //super 编译器符号
  18. //调用父类的方法
  19. self = [super init];
  20. if(self)
  21. {
  22. _color = 1;
  23. }
  24. return self;
  25. }
  26. -(void)printMe
  27. {
  28. NSLog(@"%d",_color);
  29. }
  30. @end
  1. // main.m
  2. // 构造方法
  3. //
  4. // Created by Aaron on 15/5/18.
  5. // Copyright (c) 2015年 Aaron. All rights reserved.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import "Cat.h"
  9. int main(int argc, const char * argv[])
  10. {
  11. @autoreleasepool {
  12. //构造方法
  13. //init或者以init开头的方法
  14. Cat *cat = [[Cat alloc] init];
  15. // [cat init];
  16. [cat printMe];
  17. //匿名对象
  18. NSLog(@"%@",[Cat alloc]);
  19. //原则上构造方法只在创建对象的时候才会使用一次,后面都不要再调用
  20. }
  21. return 0;
  22. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注