ios之点语法

时间:2023-03-08 20:33:28

第一个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. #import <Foundation/Foundation.h>
  9. @interface Person : NSObject
  10. {
  11. int _age;//默认为@protected
  12. }
  13. - (void)setAge:(int)age;
  14. - (int)age;
  15. @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. #import "Person.h"
  9. @implementation Person
  10. - (void)setAge:(int)age
  11. {
  12. _age = age;//注意不能写成self.age = newAge,相当与 [self setAge:newAge];
  13. }
  14. - (int)age//object C 的调用get方法的命名习惯是直接用属性名,而不加get前缀,如getAge等。
  15. {
  16. return _age;
  17. }
  18. @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. #import <Foundation/Foundation.h>
  9. #import "Person.h"
  10. int main(int argc, const char * argv[])
  11. {
  12. @autoreleasepool {
  13. // insert code here...
  14. Person *person = [[Person alloc] init];
  15. //[person setAge:10];
  16. person.age = 10;//点语法,等效与[person setAge:10];注意,这里并不是给person的属性赋值,而是调用person的setAge方法
  17. //int age = [person age];
  18. int age = person.age;//等效与int age = [person age],,你可以试着打印出来看看。
  19. NSLog(@"age is %i", age);
  20. [person release];
  21. }
  22. return 0;
  23. }

几点说明:

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

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

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

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

ios之点语法

ios之点语法

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