ios developer tiny share-20160915

来源:互联网 发布:黑手党知乎 编辑:程序博客网 时间:2024/06/16 13:53

今天讲copy关键字的用法,可以使属性不被改变。


Copy Properties Maintain Their Own Copies
In some circumstances, an object may wish to keep its own copy of any objects that are set for its properties.

As an example, the class interface for the XYZBadgeView class shown earlier in Figure 3-4 might look like this:

@interface XYZBadgeView : NSView@property NSString *firstName;@property NSString *lastName;@end

Two NSString properties are declared, which both maintain implicit strong references to their objects.

Consider what happens if another object creates a string to set as one of the badge view’s properties, like this:

NSMutableString *nameString = [NSMutableString stringWithString:@"John"];self.badgeView.firstName = nameString;

This is perfectly valid, because NSMutableString is a subclass of NSString. Although the badge view thinks it’s dealing with an NSString instance, it’s actually dealing with an NSMutableString.

This means that the string can change:

[nameString appendString:@"ny"];

In this case, although the name was “John” at the time it was originally set for the badge view’s firstName property, it’s now “Johnny” because the mutable string was changed.

You might choose that the badge view should maintain its own copies of any strings set for its firstName and lastName properties, so that it effectively captures the strings at the time that the properties are set. By adding a copy attribute to the two property declarations:

@interface XYZBadgeView : NSView@property (copy) NSString *firstName;@property (copy) NSString *lastName;@end

the view now maintains its own copies of the two strings. Even if a mutable string is set and subsequently changed, the badge view captures whatever value it has at the time it is set. For example:

NSMutableString *nameString = [NSMutableString stringWithString:@"John"];self.badgeView.firstName = nameString;[nameString appendString:@"ny"];

This time, the firstName held by the badge view will be an unaffected copy of the original “John” string.

The copy attribute means that the property will use a strong reference, because it must hold on to the new object it creates.

Note: Any object that you wish to set for a copy property must support NSCopying, which means that it should conform to the NSCopying protocol.
Protocols are described in Protocols Define Messaging Contracts. For more information on NSCopying, see NSCopying or the Advanced Memory Management Programming Guide.
If you need to set a copy property’s instance variable directly, for example in an initializer method, don’t forget to set a copy of the original object:

- (id)initWithSomeOriginalString:(NSString *)aString {    self = [super init];    if (self) {        _instanceVariableForCopyProperty = [aString copy];    }    return self;}


0 0