[关闭]
@fiy-fish 2015-07-14T11:21:41.000000Z 字数 1025 阅读 1139

day01-05-构造方法

Objective-c


  1. // day01-05-构造方法
  2. //
  3. // Created by Aaron on 15/7/1.
  4. // Copyright (c) 2015年 Aaron. All rights reserved.
  5. //
  6. #import <Foundation/Foundation.h>
  7. #import "Clothes.h"
  8. int main(int argc, const char * argv[]) {
  9. @autoreleasepool {
  10. //初始化---对象产生的时候就已经给实例变量赋值的过程
  11. //构造方法---init或者以init开头的方法
  12. //作用是给对象初始化
  13. //构造方法在创建对象的时候必须调用一次
  14. Clothes *c = [Clothes alloc];
  15. c = [c init];
  16. //[c setColors:"red"];
  17. [c showColor];
  18. }
  19. return 0;
  20. }

  1. #import <Foundation/Foundation.h>
  2. @interface Clothes : NSObject
  3. {
  4. char _colors[20];
  5. char *_ss;
  6. }
  7. //设值
  8. -(void)setColors:(char *)color;
  9. //显示
  10. -(void)showColor;
  11. @end

  1. #import "Clothes.h"
  2. @implementation Clothes
  3. //id 泛型对象指针,可以指向任意类型的对象
  4. //instancetype 关联方法
  5. -(instancetype)init
  6. {
  7. //self是一个指针
  8. //表示对象自身
  9. //self就是消息的接收者
  10. //super 是一个编译器符号
  11. //表示调用父类的方法
  12. if(self = [super init])
  13. {
  14. strcpy(_colors, "black");
  15. }
  16. return self;
  17. }
  18. -(id)test1
  19. {
  20. return [[Clothes alloc] init];
  21. }
  22. //instancetype 表示只能返回当前类的对象
  23. //也是泛型,在不同的类里面出现,就表示不同的对象类型
  24. //instancetype 做返回值的方法叫做关联方法
  25. //只能做返回值类型
  26. //但是id可以做参数
  27. -(instancetype)test2
  28. {
  29. return [[Clothes alloc] init];
  30. }
  31. -(void)setColors:(char *)color
  32. {
  33. strcpy(_colors, color);
  34. }
  35. -(void)showColor
  36. {
  37. NSLog(@"....%s",_colors);
  38. }
  39. @end
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注