您的位置:首页 > 职场人生

黑马程序员-@property,@synthesize使用细节和id

2014-09-09 23:55 507 查看
一、@property@synthesize 关键字以及使用细节

这两个关键字是编译器的特性,帮助我们有效的减少不必要代码的书写。

1.@property可以自动生成某个成员变量的setter和getter方法声明

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
int _age;
// int age;
int _height;
double _weight;
NSString *_name;
}

// @property:可以自动生成某个成员变量的setter和getter声明
@property int age;
//- (void)setAge:(int)age;
//- (int)age;

@property int height;
//- (void)setHeight:(int)height;
//- (int)height;

- (void)test;

@property double weight;

@property NSString *name;

@end


这里注意不可以写成@property int _age;这样写的话会默认声明: - (void)setAge:(int)_age;- (int)_age; 就无法调用p.age或者[p setAge:10];只能这样调用p._age;或者[p set_age:10];

@synthesize可以自动生成某个成员变量的setter和getter方法

#import "Person.h"

@implementation Person

// @synthesize自动生成age的setter和getter实现,并且会访问_age这个成员变量
@synthesize age = _age;

@synthesize height = _height;

@synthesize weight = _weight, name = _name;

@end


这里注意@synthesize age = _age;不可以写成@synthesize age = age;或者@synthesize age;这样写的话会自动访问age这个变量而不是_age这个成员变量(假设@interface中有声明age这个变量)

2.其实还有更简便的方法,@interface中去掉成员变量的声明。但是注意如果@interface中没有声明成员变量,那么会自动生成@private类型成员变量。如果想要成员变量为@protected类型的,方便子类访问,那么只能在@interfae中声明了。

#import <Foundation/Foundation.h>

@interface Car : NSObject
{
//int _speed;
//int _wheels;
}
@property int speed;
@property int wheels;

//@property int speed, wheels;
- (void)test;
@end


#import "Car.h"

@implementation Car
//@synthesize speed = _speed, wheels = _wheels;
// 会访问_speed这个成员变量,如果不存在,就会自动生成@private类型的_speed变量
@synthesize speed = _speed;
@synthesize wheels = _wheels;

- (void)test
{
NSLog(@"速度=%d", _speed);
}

@end


3.在Xcode4.4以后,@proterty关键字会自动声明和实现成员变量的setter和getter方法,无需@synthesize关键字

#import <Foundation/Foundation.h>

@interface Dog : NSObject
@property int age;
@end


#import "Dog.h"

@implementation Dog

@end


这里要注意几点:

1>如果手动实现了set方法,那么编译器就只生成get方法和成员变量;

2>如果手动实现了get方法,那么编译器就只生成set方法和成员变量;

3>如果set和get方法都是手动实现的,那么编译器将不会生成成员变量。

二、id

>万能指针,能够指向任何OC对象,相当于NSObject *

>id类型的定义:

typedef struct objc_object
{
Class isa;
} *id;


>注意id后面不要加*

id p = [person new];


>局限性:调用一个不存在的方法,编译器会立马报错。

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property int age;
@property id obj;
@end


#import "Person.h"

@implementation Person

@end


#import <Foundation/Foundation.h>
#import "Person.h"

void test(id d)
{

}

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

@autoreleasepool {
Person *p = [Person new];
NSObject *o = [Person new];
// id  == NSObject *
// 万能指针,能指向\操作任何OC对象
id d = [Person new];

[d setAge:10];
// 可以传任何对象
[d setObj:@"321423432"];

NSLog(@"%d", [d age]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐