13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 2: Object-Oriented Programming 39Additionally, an object’s instance variables can also be declared within this block in a mannersimilar to that used within the @interface block seen earlier. Note, however, all variables mustbe placed together in the same place. You can’t put some variables in the @interface block andsome in the @implementation. Listing 2-12 shows this in action.Listing 2-12. A Sample Object Implementation@implementation MyObject{int aValue;}@synthesize value = aValue;+ (id) objectWithValue: (int) value{return ( [[self alloc] initWithValue: value] );}- (id) initWithValue: (int) value{self = [super init];if ( self == nil )return ( nil );aValue = value;}return ( self );- (id) init{// call through to the designated initializerreturn ( [self initWithValue: 0] );}@endHere you can see the definitions of a class method and two initializers, as well as a few newkeywords.First is the @synthesize statement: this is the counterpart to a @property declaration in theclass’s interface. Following the keyword is either a comma-separated list of property names or alist of property-name/variable-name pairs. In the former case, the compiler pairs the property toan identically-named instance variable. If one has been specified already, it uses that; otherwiseit will create one for you at runtime. In the latter case, an instance variable has already beendeclared, and the @synthesize statement simply tells the compiler to use that variable to storethe property’s value. These must have the exact same type or the compiler will complain. InListing 2-12 the value property is told to use the aValue instance variable as its storage.Most programmers prefer to explicitly name the backing variables for their properties, using@synthesize myVar = _myVar or similar. We recommend using this only when exposing an internalwww.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!