Upload
frank-wang
View
219
Download
0
Embed Size (px)
Citation preview
7/25/2019 Properties Objective C
1/7
PropertiesThe goal of the @property directive is to make it easy to create and congureproperties by automatically generating these accessor methods. It allows youto specify the behavior of a public property on a semantic level, and it takescare of the implementation details for you.
The @property Directive
// Car.himport !"oundation/"oundation.h#
@interface Car $ %&'b(ect
@property )''* running+
@end
// Car.mimport Car.h
@implementation Car
@synthesi-e running running+ // 'ptional for 0code 1.12
@end
3 4)''*5running 6 return running+73 4void5set8unning$4)''*5new9alue 6 running new9alue+7
7/25/2019 Properties Objective C
2/7
:fter declaring the property with the @property directive, you can callthese methods as if they were included in your class;s interface andimplementation les. honda ??Car alloc init+honda.running
7/25/2019 Properties Objective C
3/7
7
@end
The readonly attribute is an easy way to make a property read3only. It
omits the setter method and prevents assignment via dot3notation, butthe getter is unaDected
8emember that @property also generates an instance variable for us,which is why we can access running without declaring it anywhere 4wecan;t use self.running here because the property is read3only5.
The nonatomic Attribute
:tomicity has to do with how properties behave in a threadedenvironment. Ehen you have more than one thread, it;s possible for thesetter and the getter to be called at the same time. This means that thegetter/setter can be interrupted by another operation, possibly resultingin corrupted data.
:tomic properties lock the underlying ob(ect to prevent this fromhappening, guaranteeing that the get or set operation is working with acomplete value. =owever, it;s important to understand that this is onlyone aspect of thread3safetyFusing atomic properties does not necessarilymean that your code is thread3safe.
Groperties declared with @property are atomic by default, and this doesincur some overhead. &o, if you;re not in a multi3threaded environment 4oryou;re implementing your own thread3safety5, you;ll want to override thisbehavior with the nonatomic attribute, like so$
@property 4nonatomic5 %&&tring >model+ :ccessors for atomic properties must bothbe either generated or user3
dened. 'nly non3atomic properties let you mi3and3match synthesi-edaccessors with custom ones
Memory Management
'b(ective3C uses a more eHcient alternative called ob(ect ownership.Ehen you start interacting with an ob(ect, you;re said to ownthat ob(ect,which means that it;s guaranteed to eist as long as you;re using it. Ehenyou;re done with it, you relinuish ownership, andFif the ob(ect has noother ownersFthe operating system destroys the ob(ect and frees up the
underlying memory.
7/25/2019 Properties Objective C
4/7
The strong Attribute
// Gerson.himport !"oundation/"oundation.h#
@interface Gerson $ %&'b(ect
@property 4nonatomic5 %&&tring >name+
@end
// Gerson.mimport Gerson.h
@implementation Gerson
3 4%&&tring >5description 6 return self.name+7
@end
// Car.himport !"oundation/"oundation.h#import Gerson.h
@interface Car $ %&'b(ect
@property 4nonatomic5 %&&tring >model+@property 4nonatomic, strong5 Gerson >driver+
@end
// main.mimport !"oundation/"oundation.h#import Car.h
import Gerson.h
int main4int argc, const char > argv?5 6 @autoreleasepool 6 Gerson >(ohn ??Gerson alloc init+ (ohn.name @John+
Car >honda ??Car alloc init+
7/25/2019 Properties Objective C
5/7
honda.model @=onda Civic+ honda.driver (ohn+
%&*og4@B@ is driving the B@, honda.driver, honda.model5+ 7
return K+7
The strong attribute creates an owning relationship to whatever ob(ect isassigned to the property. This is the implicit behavior for all ob(ectproperties, which is a safe default because it makes sure the value eistsas long as it;s assigned to the property.
&ince driver is a strong relationship, the honda ob(ect takes ownership of(ohn. This ensures that it will be valid as long as honda needs it.
The weak Attribute
// Gerson.himport !"oundation/"oundation.h#
@class Car+
@interface Gerson $ %&'b(ect
@property 4nonatomic5 %&&tring >name+@property 4nonatomic, strong5 Car >car+
@end
The @class Car line is a forward declaration of the Car class. It;s liketelling the compiler, LTrust me, the Car class eists, so don;t try to nd itright now.M Ee have to do this instead of our usual import statementbecause Car also imports Gerson.h, and we would have an endless loop ofimports. 4Compilers don;t like endless loops.5
=owever, strong references pose a problem if, for eample, we need areference from driver back to the Car ob(ect he;s driving. "irst, let;s add acar property to Gerson.h$
%et, add the following line to main.m right after the honda.driverassignment$
honda.driver (ohn+
(ohn.car honda+ // :dd this line
Ee now have an owning relationship from honda to (ohn and anotherowning relationship from (ohn to honda. This means that both ob(ects will
7/25/2019 Properties Objective C
6/7
alwaysbe owned by another ob(ect, so the memory management systemwon;t be able to destroy them even if they;re no longer needed.
This is called a retain cycle, which is a form of memory leak, and memoryleaks are bad. "ortunately, it;s very easy to this problemF(ust tell oneof the properties to maintain a weak reference to the other ob(ect. InGerson.h, change the car declaration to the following
The weak attribute creates a non3owning relationship to car. This allows(ohn to have a reference to honda while avoiding a retain cycle. )ut, thisalso means that there is a possibility that honda will be destroyed while
(ohn still has a reference to it. &hould this happen, the weak attribute willconveniently set car to nil in order to avoid a dangling pointer
: common use case for the weak attribute is parent3child data structures.)y convention, the parent ob(ect should maintain a strong reference with
it;s children, and the children should store a weak reference back to theparent
The copy Attribute
// Car.h@property 4nonatomic, copy5 %&&tring >model+
// main.mimport !"oundation/"oundation.h#import Car.h
int main4int argc, const char > argv?5 6 @autoreleasepool 6 Car >honda ??Car alloc init+ %&Nutable&tring >model ?%&Nutable&tring stringEith&tring$@=ondaCivic+ honda.model model+
7/25/2019 Properties Objective C
7/7
%&*og4@B@, honda.model5+ ?model set&tring$@%issa 9ersa+ %&*og4@B@, honda.model5+ // &till =onda Civic 7 return K+
7
The copy attribute is an alternative to strong. Instead of taking ownershipof the eisting ob(ect, it creates a copy of whatever you assign to theproperty, then takes ownership of that. 'nly ob(ects that conform to the%&Copying protocolcan use this attribute.
Groperties that represent values 4opposed to connections or relationships5are good candidates for copying. "or eample, developers usually copy%&&tring properties instead of strongly reference them$
%&Nutable&tringis a subclass of %&&tring that can be edited in3place. Ifthe model property didn;t create a copy of the original instance, we wouldbe able to see the altered string 4%issan 9ersa5 in the second%&*og45output.
https://developer.apple.com/library/ios/documentation/cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSCopyinghttp://rypress.com/tutorials/objective-c/data-types/nsstring.html#nsmutablestringhttp://rypress.com/tutorials/objective-c/data-types/nsstring.html#nsmutablestringhttps://developer.apple.com/library/ios/documentation/cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSCopying