您的位置:首页 > 移动开发 > IOS开发

IOS中"声明属性"和类成员变量的关系

2012-11-04 18:03 405 查看
用apple的官方文档《The Objective-C Programming Language》

来说明这个问题:

参见Declared Properties章节:

@property

You can think of a property declaration as being equivalent to declaring two accessor methods. Thus

@property float value;

is equivalent to:

- (float)value;
- (void)setValue:(float)newValue;

@synthesize

You use the @synthesize directive to tell the compiler that it should
synthesize the setter and/or getter

methods for a property if you do not supply them within the @implementation block.
The @synthesize

directive also synthesizes an appropriate instance variable if it is not otherwise declared
.

@interface MyClass : NSObject
@property(copy, readwrite) NSString *value;
@end
@implementation MyClass
@synthesize value;
@end


同时呢,也复习了下如何使用属性:

1.Property Redeclaration

// public header file
@interface MyObject : NSObject
@property (readonly, copy) NSString *language;
@end
// private implementation file
@interface MyObject ()
@property (readwrite, copy) NSString *language;

@end
@implementation MyObject
@synthesize language;
@end


2.Core Foundation

@interface MyClass : NSObject
@property(readwrite) CGImageRef myImage;
@end
@implementation MyClass
@synthesize myImage;
@end


3.Subclassing with Properties

you could define a class MyInteger

with a readonly property, value:

@interface MyInteger : NSObject
@property(readonly) NSInteger value;
@end
@implementation MyInteger
@synthesize value;
@end


You could then implement a subclass, MyMutableInteger, which redefines the property to make it writable:

@interface MyMutableInteger : MyInteger
@property(readwrite) NSInteger value;
@end
@implementation MyMutableInteger
@dynamic value;
- (void)setValue:(NSInteger)newX {
value = newX;
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: