oc学习笔记2—— 点语法 @property @synthesize

先来几段代码,Dog类的.h .m文件 和main.m

dog.h

#import <Foundation/Foundation.h>

@interface Dog : NSObject
{
    int _ID;
    NSString *_name;
    int _age;
    float _price;
}
//凡是用initXXX开头的都是构造函数
//init方法实际上没有什么特别的,只是遵循命名约定的普通方法
-(id)init;
-(id)initWithID:(int)newID;
-(id)initWithID:(int)newID andAge:(int)newAge;
-(id)initWithID:(int)newID andAge:(int)newAge andPrice:(int)newPrice;
@property int ID;
@property NSString *name;
@property int age;
@property float price;
@end

dog.m

#import "Dog.h"

@implementation Dog
-(id)init
{
    return [self initWithID:1001];

}
-(id)initWithID:(int)newID
{
    return [self initWithID:newID andAge:20];
}
-(id)initWithID:(int)newID andAge:(int)newAge
{
    return [self initWithID:newID andAge:newAge andPrice:80.0];
}
-(id)initWithID:(int)newID andAge:(int)newAge andPrice:(int)newPrice
{
    self=[super init];
    if(self){
        _ID=newID;
        _age=newAge;
        _price=newPrice;
    }
    return self;
}

@synthesize ID=_ID;
@synthesize name=_name;
@synthesize age=_age;
@synthesize price=_price;

@end

main.m

#import <Foundation/Foundation.h>
#import "Dog.h"
#import "NSString+ReverseString.h"
#import "Person.h"

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

    @autoreleasepool {
        Dog *dog1=[[Dog alloc ] init];
        dog1.name=@"syj";
        NSLog(@"%@",[dog1 name]);
        [dog1 setName:@"ldusyj"];
        NSLog(@"%@",dog1.name);
    }
    return 0;
}


先看一下:

@property

@property int age;

等同于  -setAge:(int)newAge;

 -(void)age;

@synthesize

@synthesize age=_age;

等同于:  -(void)setAge:(int)newAge{

age=newAge;

} 

-(int)age{

return age;

}

在看一下点:

1.

dog1.name=@"syj";
点放到左边相当于调用其对应的set方法。

等同

[dog1 setName:@"syj"];
2.

NSLog(@"%@",dog1.name);
NSLog(@"%@",[dog1 name]);
这两种情况是相同的效果。相当于get方法。


注意:

-(void)setAge:(int)newAge 
{ 
    NSLog(@"调用了setAge方法:%i",newAge); 
    self.age = newAge; 
}


不能在setAge:方法中使用self.age  =  newAge,相当于在setAge:方法中调用[self  setAge:newAge ], 出现死循环

-(int)age 
{ 
    NSLog(@"调用了age方法:%i",_age); 
    return self.age; 
}

不能在age方法中使用return    self.age,   相当于return    [self age];,   出现了死循环


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值