第一个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:
- //
- // Person.h
- // 点语法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- {
- int _age;//默认为@protected
- }
- - (void)setAge:(int)age;
- - (int)age;
- @end
Person.m
- //
- // Person.m
- // 点语法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import "Person.h"
- @implementation Person
- - (void)setAge:(int)age
- {
- _age = age;//注意不能写成self.age = newAge,相当与 [self setAge:newAge];
- }
- - (int)age//object C 的调用get方法的命名习惯是直接用属性名,而不加get前缀,如getAge等。
- {
- return _age;
- }
- @end
main.m
- //
- // main.m
- // 点语法
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Person.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- // insert code here...
- Person *person = [[Person alloc] init];
- //[person setAge:10];
- person.age = 10;//点语法,等效与[person setAge:10];注意,这里并不是给person的属性赋值,而是调用person的setAge方法
- //int age = [person age];
- int age = person.age;//等效与int age = [person age],,你可以试着打印出来看看。
- NSLog(@"age is %i", age);
- [person release];
- }
- return 0;
- }
几点说明:
1.根据 Objective-C.Programming.The.Big.Nerd.Ranch.Guide.Jan.2012这本书里说的,,点语法一般不常用,经常用的是中括号的形式。如 [ person age]这样的形式。
2.函数前面的“-”代表的是动态方法,静态方法用”+“,,”-“和”+“都不能省略,不然编译器会报错。
3.点语法的本质是调用get方法和set方法。
4.不要忘了[person release]这句。
版权声明:本文为博主原创文章,未经博主允许不得转载。