先来几段代码,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];, 出现了死循环