我会慢慢翻译的,getter和setter方法在别处生成了普京网址(比如父类中)

Objective-C Properties,objective-c

Objective-C Properties

Apple introduced properties, a combination of new compiler directives
and a new attribute accessor syntax.

Apple 引入了属性这一概念。新的编译器命令和新的属性存取句法。

1.1 Shrinking the Interface 减少interface代码

 

@property float rainHandling; says that objects of the class
AllWeatherRadial have an attribute, of type float, called rainHandling.
It also says that you can set the property by calling –setRainHanding:
and that you can access the attribute by calling -rainHandling.

@property float rainHandling;这个说明这个对象有一个类属性,是float
类型,名字为rainHandling 。同样,你能够通过调用setRainHanding
设置属性值。

1.2 Shrinking the Implementation

@synthesize rainHandling;

@synthesize snowHandling;

@synthesize is a compiler feature that says “create the accessors for
this attribute.”

@ synthesize是编译器特色,说创建这个属性的获取。 

 

@synthesize is not code generation. You won’t ever see the code that
implements –setRainHandling: and –rainHandling, but these methods will
exist and will be callable.

@synthesize 不是代码生成器。但是这项方法存在,且能被调用。

If you provide the methods in your class for the property, the compiler
doesn’t create them. The compiler only creates methods that are missing.

如果你提供了这个属性的一个方法,那么compiler将不创建这些方法。compiler

只创建缺失的方法。

Most properties are backed by a variable, so when you synthesize the
getter and setter, the compiler automatically creates an instance
variable with the same name as the property.

大部分properties 返回一个variable ,所以当你同步getter
和setter方法的时候,compiler 自动创建了与这个属性名字相同的实例变量。

Notice that the header file has two variables called rainHandling and
snowHandling. The setter and getter will use these variables. If you
don’t declare those variables, the compiler creates them.

注意头文件有两个变量,如果没写的话,compiler将自动添加这两个方法。

1.3 Dot notation 

The dot notation looks a lot like structure access in C and object
access in Java—on purpose.

点运算符想存储在C和对象存取在java中一样

1.4 Objecting to Properties 对象 对于属性

Objects bring some added complications.

对象让事情麻烦了。

Recall that we retain and release objects as they flow through our
accessors.

当他们要经过accessor时,我们retain 和release 对性。

For some object values, particularly string values, you want to always
-copy them. Yet for other object values, like delegates (which we’ll
talk about in the next chapter), you don’t want to retain them at all.

像string你想copy 它,而对于delegate ,你却不想retain 他们。

@property (copy) NSString *name;

@property (retain) Engine *engine;

 

 

You can use some other decorations, like nonatomic, which makes
accessors a bit faster if they won’t be used in a multithreaded
environment.

如果 他们不用在多线程环境,nonatomic 使得accessor更快,

 

s. You can also use assign if you don’t want the attribute object to be
retained, to help avoid retain cycles.

如果你不想属性对象被retained ,那么我们将尽量避免retian 循环。

You can only specify retain and copy attributes for retainable pointers
(i.e. Objective-C objects). All other types, such as C and nonretainable
pointers, must use assign and manage memory manually.

 

If you provide either or both the setter and getter yourself, you cannot
use atomic attribute; you must use nonatomic.

如果你自己写了setter 或getter方法中任意一个,那么你不能用atomic
属性,必须使用nontomic 属性。

 

1.5 Appellation spring  别名

the name of the property has been the same as the name of an instance
variable that backs that property.

一般情况下,property的名字应该和返回的property的实例变量名字一样。 

Sometimes, though, you may want one name for the instance variable and
another for the public attribute name.

但是有些时候你想让实例变量一个名字,而公共属性名字为另一个。

@interface Car : NSObject

{

  NSString *appellation;

  NSMutableArray *tires;

  Engine *engine;

}

@property (copy) NSString *name;

@property (retain) Engine *engine;

and then change the synthesize directive: @synthesize name =
appellation;

 

In init, change

name = @”Car”;

to

self.name = @”Car”;

 

 

 

What’s that self-dot-name business? It’s a bit of disambiguation to let
the compiler know that we want to vector through the accessors. If we
just use a naked name, the compiler assumes that we’re directly
modifying an instance variable. To go through the accessors, we can
write [self setName:@”Car”]. Remember that the dot is just shorthand
for making this exact same call, so self.name = @”Car” is just another
way of saying the same thing.

 

只是为了去除歧义。

 

1.6 Read-Only About It只读 

You might have an object with an attribute that is read-only.

有一些属性你允许它只能读。

You can code for these situations with more attributes on @property.

你可以在@property中加attribute

 

By default, properties are mutable: you can read and write them.
Properties have a readwrite attribute you can use for specifying this.

默认情况下,properties 是可变的。你能读和写他们。

@property (readonly) float shoeSize;

@property (readonly) NSString *licenseNumber;

When the compiler sees that @property is readonly, it generates a getter
but not a setter for that attribute.

当compiler 看到@property 只读时,应该只产生getter方法,而不产生setter
方法。

1.7 

What if you’d rather not have a variable, getter, and setter for your
property?

如果你getter 和setter方法都不想要的话怎么办?

You can use the keyword @dynamic to tell the compiler not to generate
any code or create a variable for the property.

你可以用关键则@dynamic 来告诉编译器不产生任何代码。

@property (readonly) float bodyMassIndex;

@dynamic bodyMassIndex;

– (float)bodyMassIndex

{

 ///compute and return bodyMassIndex

}

1.8 chang the method name

you might not like the names of the methods that are generated by
default. They’re in the form of blah and setBlah:.

有时候你想用自己的方法名字。

To overcome this, you can specify the names of the getter and setter
that the compiler generates. Use the attributes getter= and setter= to
define the preferred names of your methods.

为此,你应该在@property设置getter= and setter attribute . 

@property (getter=isHidden) BOOL hidden;

1.9 properties 并不是无所不能

– (void) setTire: (Tire *) tire atIndex: (int) index;

– (Tire *) tireAtIndex: (int) index;

these methods don’t fit into the fairly narrow range of methods that
properties cover. Properties will let you replace only –setBlah and
–blah methods, but not methods that take extra arguments, like the
tire’s position on the car.

上面的方法并不适合properties .因为属性仅仅允许你替换setter和getter
方法不带参数的部分。

Properties,objective-c Objective-C
Properties Apple introduced properties, a combination of new compiler
directives and a new attribute accessor syntax. Apple 引入了…

By
default, properties are mutable: you can read and write them. Properties
have a readwrite attribute you can use for specifying this.

However, a few exceptions exist:

Creating Objects
    Any time you create an object using the alloc/init pattern, you
build it with a retain count of one. It doesn’t matter which class you
use or what object you build, alloc/init produces  a +1 count.
    For locally scoped variables, if you do not release the object
before the end of a method, the object leaks. Your reference to that
memory goes away, but the memory itself remains allocated. The retain
count remains at +1.

Uses for @dynamic are e.g. with subclasses of NSManagedObject(CoreData)
or when you want to create an outlet for a property defined by a
superclass that was not defined as an outlet;

{

○ readonly property with custom getter

when providing a custom getter implementation for a readonly property,
this won’t be automatically synthesized

A third attribute called copy sends a copy message to the passed object,
retains it, and releases any previous value.
@property (copy) NSString *make;

@dynamic
会告诉编译器:getter和setter方法在别处生成了(比如父类中),并没有在本类生成。

如果你getter
和setter方法都不想要的话怎么办?

@synthesize propertyName = _propertyName

Simple Memory Management.
Memory management comes down to two simple rules.
At creation, every object has a retain count of one.
At release, every object has a retain count of zero.
Complicating matters is OC’s autorelease pool

@synthesize will generate getter and setter methods for your property.

To
overcome this, you can specify the names of the getter and setter that
the compiler generates. Use the attributes getter= and setter= to define
the preferred names of your methods.

Category 中声明的属性

这种情况,@synthesize
指令不但不能被编译器自动生成,也不能手动合成属性。虽然category可以声明属性,但不能合成,因为category不能创建类实例变量ivars.为了完整起见,我还是加了这项,因为还是可以通过Objective-C运行时伪造合成属性

Note
Avoid assigning properties to themselves, for example, myCar.colors =
myCar.colors.The release-then-retain behavior of properties may cause
the object to deallocate before it can be reassigned and re-retained.

@dynamic just tells the compiler that the getter and setter methods are
implemented not by the class itself but somewhere else(like the
superclass)

 

Setting the property’s attribute to retain does two things.
First, it retains the passed object upon assignment.
Second, it releases the previous value before a new assignment is
made.
To create a retained property, add the attribute between parentheses in
the declaration:
@property (retain) NSString *make;

  1. @property中的 @synthesize 和 @dynamic 区别:

The dot
notation looks a lot like structure access in C and object access in
Java—on purpose.

○ properties declared in a @protocol

when conforming to a protocol, any property the protocol defines won’t
be automatically synthesized

Property Attributes
The default behavior for properties is assign.

运行时动态创建绑定:主要使用在CoreData的实现NSManagedObject子类时使用,由Core
Data框架在程序运行的时动态生成子类属性。

Notice
that the header file has two variables called rainHandling and
snowHandling. The setter and getter will use these variables. If you
don’t declare those variables, the compiler creates them.

@protocol 中定义的属性

当遵守了一个协议,任何协议定义的属性都不会自动合成

As a general rule of thumb, Apple recommends you avoid using properties
in your functions. Instead, use instance variables directly.

@synthesize 能够为你的属性自动生成getter和setter方法。

For some
object values, particularly string values, you want to always -copy
them. Yet for other object values, like delegates (which we’ll talk
about in the next chapter), you don’t want to retain them at all.

只读属性的自定义getter

当给只读属性提供一个自定义getter 实现时,不会自动合成

Property
OC automatically builds methods when you @synthesize properties.Notice
the capitalization of the second word in the set method. By convention,
OC expects setters to use a method named setInstance: where the first
letter of the instance variable name is capitalized.

注意头文件有两个变量,如果没写的话,compiler将自动添加这两个方法。

○ readwrite property with custom getter and setter

when providing both a getter and setter custom implementation, the
property won’t be automatically synthesized

The UIApplication and UIDevice classes let you access information about
the currently running application and the device hardware it is running
on. They do so by offering singletons, that is , a sole instance of a
class in the current process.

如果
他们不用在多线程环境,nonatomic 使得accessor更快,

原文:

You can send retain to autorelease objects just like any other object.
Retaining objects set to autorelease allows them to persist beyond a
single method. Once retained, an autorelease object is just as subject
to memory leaks as one that you created using alloc/init.
By creating a reference, you can both use a retained object through its
lifetime and be able to release it when you’re done. Set references via
an instance variable (preferred) or a static variable defined within
your class implementation. If you want to keep things simple and
reliable, use retained properties built from those instance variables.

You can
use the keyword @dynamic to tell the compiler not to generate any code
or create a variable for the property.

重写属性

当重写一个父类的属性,必须显示合成它。值得注意的是,合成一个属性会自动合成backing
ivar,如果缺少属性合成,ivar也会消失,除非显示声明。

除了后三个情况,基本思想是当手动指定所有属性相关的信息(通过实现所有访问器方法或使用@dynamic),编译器会认为你想完全控制属性,他会禁用自动合成功能。

除了上面列举的情况,唯一使用显示@synthesize的是指定一个不同的实例变量名。依照惯例,我建议始终使用默认命名。

Creating Autoreleased Objects
As a rule, whenever you ask another method to create an object, it’s
good programming practice to return that object autoreleased.

@property
float rainHandling; says that objects of the class AllWeatherRadial have
an attribute, of type float, called rainHandling. It also says that you
can set the property by calling –setRainHanding: and that you can access
the attribute by calling -rainHandling.

@dynamic

当使用@dynamic propertyName, 属性不会自动合成 (很明显,@dynamic 和
@synthesize 是互斥的)

As a rule of thumb, if you build an object using any method whose name
includes alloc, new, create, or copy, you maintain responsibility for
releasing the object. Unlike class convenience methods, methods that
include these words generally do not return autoreleased objects.
Sending a copy message to an object, for example, duplicates it. Copy
returns an object with a retain count of +1 and no assignment to the
autorelease pool. Use copy when you want to duplicate and make changes
to an object while preserving the original. Note that for the most part,
OC produces shallow copies of collections like arrays and dictionaries.
It copies the structure of the collection, and maintains the addresses
for each pointer, but does not preform a deep copy of the items stored
within.

 

○ properties declared in a category

this is a case in which the @synthesize directive is not automatically
inserted by the compiler, but this properties cannot be manually
synthesized either. While categories can declare properties, they cannot
be synthesized at all, since categories cannot create ivars. For the
sake of completeness, I’ll add that’s it’s still possible to fake the
property synthesis using the Objective-C runtime.

The proper way to use an alloc/init pattern is to create, use, and then
release. Releasing brings the retain count down to 0.
Autorelease objects do not require an explicit release statement for
locally scoped variables. Sending the autorelease message to an object
marks it for autorelease. When the autorelease pool drains at the end of
each event loop, it sends release to all the objects it owns.
NSArray *array = [[[NSArray alloc] init] autorelease];
By convention, all class object-creation methods return an autoreleased
object.

@property
(readonly) float shoeSize;

○ @dynamic

when using @dynamic propertyName, the property won’t be automatically
synthesized (pretty obvious, since @dynamic and @synthesize are mutually
exclusive)

The iPhone Developer’s Cookbook读书笔记,我会慢慢翻译的。

Most
properties are backed by a variable, so when you synthesize the getter
and setter, the compiler automatically creates an instance variable with
the same name as the property.

  1. Thank to autosynthesis you don’t need to explicitly synthesize the
    property as it will be automatically synthesized by the compiler as

When you develop in a multithreaded environment, you want to use atomic
methods. Xcode synthesizes atomic methods to automatically lock objects
before they are accessed or modified and unlock them after. There is no
atomic keyword.
All methods are synthesized atomically by default.
You can, however, state the opposite, allowing OC to create accessors
that are nonatomic.
@property (nonatomic, retain) NSString *make;
    Marking your properties nonatomic does speed up access, but you
might run into problems should two competing threads attempt to modify
the same property at once.Atomic properties, with their lock/unlock
behavior, ensure that an object update completes from start to finish
before that property is released to another read or change.

these
methods don’t fit into the fairly narrow range of methods that
properties cover. Properties will let you replace only –setBlah and
–blah methods, but not methods that take extra arguments, like the
tire’s position on the car.

读写属性的自定义 getter 和 setter

当提供一个自定义的getter 和setter 实现时,属性不会自动合成

When using plain (nonproperty) instance variables or assign style
properties, send release at deallocation time.

@interface Car
: NSObject

○ overridden properties (new since clang-600.0.51, shipping with Xcode 6, thanks Marc Schlüpmann)

when you override a property of a superclass, you must explicitly
synthesize it
It’s worth noting that synthesizing a property automatically synthesize
the backing ivar, so if the property synthesis is missing, the ivar will
be missing too, unless explicitly declared.

Except for the last three cases, the general philosophy is that whenever
you manually specify all the information about a property (by
implementing all the accessor methods or using @dynamic) the compiler
will assume you want full control over the property and it will disable
the autosynthesis on it.

A part from the cases I listed above, the only other use of an explicit
@synthesize would be to specify a different ivar name. However
conventions are important, so my advice is to always use the default
naming.

翻译:
有了自动合成属性,你不需要手动合成了,编译器会帮你自动完成:

@synthesize propertyName = _propertyName

然而,有一些例外存在:

一般情况下,property的名字应该和返回的property的实例变量名字一样。 

Sometimes,
though, you may want one name for the instance variable and another for
the public attribute name.

When the
compiler sees that @property is readonly, it generates a getter but not
a setter for that attribute.

Apple
引入了属性这一概念。新的编译器命令和新的属性存取句法。

发表评论

电子邮件地址不会被公开。 必填项已用*标注