Objective-C for Delphi users: Property Setters and Getters


Even though Embarcadero did a great job in abstracting the RTL and FireMonkey from iOS specifics in their latest Delphi XE 4 release, there will sometimes be the need to access iOs APIs directly – just like we did with the Windows API.
In contrast to the Win32 API, many iOS APIs (not all though) are object oriented. For example there is a UIView class which is the base class for all visual elements. One other prominent class is NSString, which obviously handles strings. (“NS” btw. originates from “NexXTSTEP”, Steve Job’s Operating System that he developed, before he came back to Apple)
iOS / Objective-C have (like Delphi) a concept of properties, accessing their values is a little uncommon though:
Lets assume we have a Delphi TFoo class, which has a String property name, then you can read and write a Foo’s name like this:

LFoo.Name := ‘Joe’;
LName := LFoo.Name;

Once you have an instance of an iOS class and you want to access some property, intuitively you would try like this:

LView: UIView;
LMode: Cardinal;
… //instantiating UI classes will
… //be covered in a later blog post
LMode := LView.ContentMode; //works
LView.ContentMode := UIViewContentModeScaleAspectFit; //Does not work

The compiler will say “nay” though and it looks like we had a read only property here, which is not the case. The point is that Objective-C has a different syntax for properties. Access to a property ALWAYS goes through its corresponding setter and getter methods.
The getter usually has the same name as the property itself. Here we actually call a Getter function ContentMode() :

LMode := LView.ContentMode;

The setter method is usually named like the property with a “set” as prefix and of course needs to be called like a regular method with one value parameter, like this:


You will find this pattern in basically all iOS classes that have properties.
One might think “why didn’t they add some Delphi magic here?”, but I believe it is better to be close to iOS when accessing their API, so that samples etc from the iOS docs can be applied more directly.

Tweet This!

Share this on del.icio.us

Digg this!

Share this on Reddit

Get Shareaholic

Comments are closed.