ios developer tiny share-20160902

来源:互联网 发布:sublime java插件 编辑:程序博客网 时间:2024/06/05 08:50

今天接着昨天的,讲@Synthesized。另外,会讲没有@property的实例变量。

You Can Customize Synthesized Instance Variable Names

As mentioned earlier, the default behavior for a writeable property is to use an instance variable called _propertyName.

If you wish to use a different name for the instance variable, you need to direct the compiler to synthesize the variable using the following syntax in your implementation:

@implementation YourClass@synthesize propertyName = instanceVariableName;...@end

For example:

@synthesize firstName = ivar_firstName;

In this case, the property will still be called firstName, and be accessible through firstName and setFirstName: accessor methods or dot syntax, but it will be backed by an instance variable called ivar_firstName.

Important: If you use @synthesize without specifying an instance variable name, like this:

@synthesize firstName;

the instance variable will bear the same name as the property.
In this example, the instance variable will also be called firstName, without an underscore.



You Can Define Instance Variables without Properties

It’s best practice to use a property on an object any time you need to keep track of a value or another object.

If you do need to define your own instance variables without declaring a property, you can add them inside braces at the top of the class interface or implementation, like this:

@interface SomeClass : NSObject {    NSString *_myNonPropertyInstanceVariable;}...@end @implementation SomeClass {    NSString *_anotherCustomInstanceVariable;}...@end

Note: You can also add instance variables at the top of a class extension, as described in Class Extensions Extend the Internal Implementation.

0 0
原创粉丝点击