1、点语法及其好处

  1、方便程序员能够很快的转到O-C上来

  2、让程序设计简单化

  3、隐藏了内存管理细节

  4、隐藏了多线程、同步、加锁细 节

  5、点语法的使用

  Dog *dog=[[Dog aloc] init];

  [dog setAge:100];

  int dogAge=[dog age];

  NSLog(@"Dog Age is %d",dogAge);

  下面的代码用点语法

  dog.age=200;//调用setAge方法

  dogAge=dog.age;//调用age方法

  这里的点不上调用的dog这个对象的字段,而且在调用方法。dog.age是在调用setAge这个方法,下面的dog.age 是在调用age这个方法。

点语法是编译器级别

编译器会把dog.age=200;展开成[dog setAge:200];

会把dogAge=dog.age;展开成[dog age];函数调用

  6、点语法setter和getter规范

  setter函数展开规范

  dog.age=200;

  [dog setAge:200];

  getter函数展开规范

  int dogAge=dog.age;

  int dogAge=[dog age];

  项目当中如果想用点语法,必须在项目中的.h文件和.m文件中声明和实现setAge和age方法,也就是说要声明和实现getter和setter方法。

2、@property @synthesize如何使用

  @property是让编译器自动产生函数申明

  不再写下面2行代码

  -(void) setAge:(int)newAge;

  -(void) age;

  只需要下列一行就可以代替

  @property int age;

  @synthesize 意思是合成

  @synthesize就是编译器自动实现getter和setter函数

  不用写下列代码

  - (void) setAge:(int)newAge

  {

    age=newAge;

  }

  -(int) age

  {

    return age;

  }

  只需要些

  @synthesize age;

3、@property @synthesize编译器如何展开

  @property @synthesize只能展开成标准的模板,如果想在getter和setter函数中增加内容,则不能用@synthesize表示方法。

4、如何使用点语法

  self.age放在=号的左边和右边是不一样的,放在左边是表示调用setter函数,放在右边表示调用getter函数。

  为了区别开age,我们会对dog类做一些改动

  @interface Dog:NSObject

  {

    int _age;//改动了以前是int age;

  }

  @property int age;

  @end;

  #import "Dog.h"

  @implementation Dog

  @synthesize age=_age;

  @end

 

5、@property其他属性

  readwrite(缺省),readonly

    表示属性是可读写的,也就是说可以使用getter和setter,而readonly只能使用getter

    assign(缺省),retain,copy

    表示属性如何存储

    nonatomic

    表示不用考虑线程安全问题

    getter=......,setter=......

    重新设置getter函数和setter函数名

这个项目的代码如下;

dog.h文件代码

View Code
#import <Foundation/Foundation.h>

@interface Dog : NSObject
{
    int _age;
}
//setter and getter function
//- (void) setAge:(int)newAge;
//- (int) age;
@property int age;
@end

dog.m文件代码

View Code
#import "Dog.h"

@implementation Dog
@synthesize age=_age;
//- (void) setAge:(int)newAge
//{
//    age=newAge;
//}
//- (int) age
//{
//    return age;
//}
@end

main.m文件代码

View Code
#import <Foundation/Foundation.h>
#import "Dog.h"

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        
        // insert code here...
        NSLog(@"Hello, World!");
        Dog *dog=[[Dog alloc] init];
        [dog setAge:300];
        int dogAge=[dog age];
        NSLog(@"dog age is %d", dogAge);
        //classic mode
        
        Dog *dog1=[[Dog alloc] init];
        dog1.age=400;
        //[dog1 setAge:200];
        dogAge=dog1.age;
        //dogAge=[dog age];
        NSLog(@"dog1 age is %d", dogAge);

        
    }
    return 0;
}

 

posted on 2012-12-23 00:33  千里烟波226  阅读(2277)  评论(0编辑  收藏  举报