ios之点语法

第一个object c 程序

    首先新建一个项目,“create a new Xcode project"-"OS X下的Application"-"Command Line Tool" ,命名为“点语法”,Type为“Foundation”,不要勾选“Use Automatic Reference Counting”这个选项(ARC是Xcode的内存自动管理机制,刚开始学的时候先自己管理内存,以后熟悉了再勾选),,最后再新建一个类,“File”-“New”-“File”-“Cocoa”-“Object-C class",命名为“Person”,基类为“NSObject”,接下来就是代码的编写,如下:

Person.h:

  1. //  
  2. //  Person.h  
  3. //  点语法  
  4. //  
  5. //  Created by Rio.King on 13-8-25.  
  6. //  Copyright (c) 2013年 Rio.King. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @interface Person : NSObject  
  12. {  
  13.     int _age;//默认为@protected  
  14. }  
  15.   
  16. - (void)setAge:(int)age;  
  17. - (int)age;  
  18.   
  19. @end  




Person.m

  1. //  
  2. //  Person.m  
  3. //  点语法  
  4. //  
  5. //  Created by Rio.King on 13-8-25.  
  6. //  Copyright (c) 2013年 Rio.King. All rights reserved.  
  7. //  
  8.   
  9. #import "Person.h"  
  10.   
  11. @implementation Person  
  12.   
  13. - (void)setAge:(int)age  
  14. {  
  15.     _age = age;//注意不能写成self.age = newAge,相当与 [self setAge:newAge];  
  16. }  
  17.   
  18. - (int)age//object C 的调用get方法的命名习惯是直接用属性名,而不加get前缀,如getAge等。  
  19. {  
  20.     return _age;  
  21. }  
  22.   
  23. @end  




main.m

  1. //  
  2. //  main.m  
  3. //  点语法  
  4. //  
  5. //  Created by Rio.King on 13-8-25.  
  6. //  Copyright (c) 2013年 Rio.King. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10. #import "Person.h"  
  11.   
  12. int main(int argc, const char * argv[])  
  13. {  
  14.   
  15.     @autoreleasepool {  
  16.           
  17.         // insert code here...  
  18.         Person *person = [[Person alloc] init];  
  19.           
  20.         //[person setAge:10];  
  21.         person.age = 10;//点语法,等效与[person setAge:10];注意,这里并不是给person的属性赋值,而是调用person的setAge方法  
  22.           
  23.         //int age = [person age];  
  24.         int age = person.age;//等效与int age = [person age],,你可以试着打印出来看看。  
  25.         NSLog(@"age is %i", age);  
  26.         [person release];  
  27.           
  28.     }  
  29.     return 0;  
  30. }  





几点说明:

1.根据 Objective-C.Programming.The.Big.Nerd.Ranch.Guide.Jan.2012这本书里说的,,点语法一般不常用,经常用的是中括号的形式。如 [ person age]这样的形式。

2.函数前面的“-”代表的是动态方法,静态方法用”+“,,”-“和”+“都不能省略,不然编译器会报错。

3.点语法的本质是调用get方法和set方法。

4.不要忘了[person release]这句。

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/chengjun/p/4867622.html