Property access to class methods in Cocoa (Objective-C) - objective-c

You can access class methods of many Apple classes as properties. Example:
[UIDevice currentDevice];
UIDevice.currentDevice;
Those are the same and both work. How can one implement the same in their classes?

You don't need to do something special for the same, it's by default nature but it's always preferable for beginners not to use dot syntax. A proper discussion is in the post below
Dot notation vs. message notation for declared properties

You don't need to do anything. You can use "dot notation" on any method, whether it was declared by a #property or or by a normal method declaration. That's true for both objects and classes.

Related

Does Apple recommend using class extensions or variable blocks in implementation?

Apple's doc mentions two ways to create private variables, namely property and ivar, but it does not say which is the preferred way. Which one is Apple's recommended approach or are they equally good in Apple's view?
#interface MyClass ()
#property (nonatomic, strong) NSObject *prop;
#end
or
#implementation MyClass {
NSObject *_prop;
}
Note - I am not asking for personal opinion, but Apple's recommendation. There are similar discussion on this but most have been viewed from personal opinion with no clarification on why one is better than the other and which way Apple advocates (though 99% of Apple sample code uses property)
You should always use #properties because they are safer (e.g. they contain the thread-safe access protection for atomic properties, etc).
And you should also always access properties via their getter/setter instead of directly accessing the instance variables (except in init methods).
As for Apple's recommendations:
Apple engineers answered that at some talks during past WWDC. Sorry no written reference, but I can confirm that they recommend properties over instance variables
In Apple's "Programming With Objective-C" Programming Guide, they mention that you should always prefer using properties over instance variables:
Although it’s best practice for an object to access its own properties using accessor methods or dot syntax, it’s possible to access the instance variable directly from any of the instance methods in a class implementation.
[...]
In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self
[...]
The exception to this rule is when writing initialization, deallocation or custom accessor methods
Actually in such Programming Guides, like here where they describe the anatomy of an ObjC class, they never mention instance variables and explain how to create them, they only explain properties, so that's a pretty strong indicator that they try to enforce them anyway.

When to use properties vs. plain ol' getters and setters

I'm just wondering about semantics. When is something truly a "property" of an object? I noticed in a lot of Apple's APIs, they explicitly define getters and setters instead of using properties (e.g. URL and setURL on NSURLRequest/NSMutableURLRequest; surely the URL seems like a "property" of an URL request, right?) I'm wondering if there's some subtle thing that I'm missing or if Apple just doesn't like properties all that much. =P
UPDATE: As of iOS 8, Apple has converted most (if not all) of their non-property getters and setters to properties. (Probably done so that Swift compatibility would be easier.)
or if Apple just doesn't like properties all that much.
The real cause is that most of the Foundation framework (let's not forget you're talking about NS* classes) is old as dirt - they have been around there since the NeXT times... At that time, the Objective-C language didn't sport the #property keyword - to emulate properties, it was necessary for the programmers to declare and implement getter and setter methods manually, this applied to Apple's code as well.
Now the Foundation framework is so fundamental that it hasn't changed a lot. It hasn't been radically rewritten and as far as I'm concerned, programmers who wrote it didn't bother rewriting all the code using the new syntax. You can see that recently added classes do in fact feature declared properties instead of getters and setters, but that's not true for older classes.
Anyway, properties declared manually and those declared using #property and #synthesize are completely equivalent. That said, there's a very minor difference when accessing them, but that doesn't belong to the declaration thingy: if you write
someObject.someProperty
in your code, the someObject must have a complete and concrete type, so if a property named someProperty is nonexistent, you'll get a compiler error. In contrast,
[someObject someProperty]
and
[someObject setSomeProperty:]
allow you the method call even if it's undeclared.
Edit:
I ask what the semantic difference between them is
So by "semantic difference", you meant "when it should be used" rather than "does it run differently". I see. Well... Conceptually, properties represent state. A property is a particular characteristic of an object that may change over time. It's just an unrelated fact that properties are accessed using accessor methods in Objecive-C.
If you write a method that acts on the obejct (other than setting a property, of course), there's a fair chance you should be declaring and calling it as a method. If you access (read or write) an attribute of an object, that better fits the task of a property.
Having a getter and setter lets you use messages to access the item
[myObject someProperty] or [myObject setSomeProperty: someNewValue]
Making something a #property gives you the additionally ability to use dot notation to call the getter and setter. This is because #property chooses method names that make the class key-value-coding compliant for the particular value.
myObject.someProperty or myObject.someProperty = someNewValue
While it is possible to do this manually, it is considered best-practice to use #property when you want to use the dot notation. Over time, the behind-the-scenes bahaviours of #property and #synthesize have changed quite a bit particularly in regard to auto-creating storage for the associated pointer. Using #property makes it easier to keep up with Apple's changes in convention with little or no change in your code.
Additionaly, using #property makes your code much easier to read.

Objective C - Using property get accessor vs directly using iVar

I was wondering what exactly are the differences between using the (get) accessor for reading the value of property and directly using the iVar?
Say I have a class which declares a property:
#interface Foo : NSObject
#property (strong) NSString *someString;
#end
And in the implementation I'm using it. Are there any differences between the following two lines:
someLabel.text = self.someString;
someLabel.text = _someString;
For set accessors it's clear. Afaik for strong properties the accessor takes care of retain and release (an interesting 'side question' would be if ARC changes that, i.e. does setting the iVar directly [assuming it's not an __weak iVar] also retain and release correctly using ARC), also KVO requires the use of accessors to work properly etc. But what about getters?
And if there's no difference, is there one way considered best practice?
Thx
As you know, calling self.someString is really [self someString]. If you chose to create a property then you should use the property. There may be other semantics added to the property. Perhaps the property is lazy loaded. Perhaps the property doesn't use an ivar. Perhaps there is some other needed side effect to calling the property's getter. Maybe there isn't now but maybe this changes in the future. Calling the property now makes your code a little more future proof.
If you have an ivar and a property, use the property unless you have explicit reason to use the ivar instead. There may be a case where you don't want any of the extra semantics or side effect of the property to be performed. So in such a case, using the ivar directly is better.
But ultimately, it's your code, your property, your ivar. You know why you added a property. You know any potential benefits of that property, if any.
I think this what you are looking for. Why use getters and setters?
There are actually many good reasons to consider using accessors rather than directly exposing fields of a class - beyond just the argument of encapsulation and making future changes easier.
Here are the some of the reasons I am aware of:
Encapsulation of behavior associated with getting or setting the
property - this allows additional functionality (like validation) to
be added more easily later.
Hiding the internal representation of the
property while exposing a property using an alternative
representation.
Insulating your public interface from change -
allowing the public interface to remain constant while the
implementation changes without effecting existing consumers.
Controlling the lifetime and memory management (disposal) semantics
of the property - particularly important in non-managed memory
environments (like C++ or Objective-C).
Providing a debugging
interception point for when a property changes at runtime - debugging
when and where a property changed to a particular value can be quite
difficult without this in some languages.
Improved interoperability
with libraries that are designed to operate against property
getter/setters - Mocking, Serialization, and WPF come to mind.
Allowing inheritors to change the semantics of how the property
behaves and is exposed by overriding the getter/setter methods.
Allowing the getter/setter to be passed around as lambda expressions
rather than values.
Getters and setters can allow different access
levels - for example the get may be public, but the set could be
protected.
I am not a very experienced person to answer this question, even though I am trying to give my views and my experience by seeing source code which is around 10yrs older.
In earlier codes they were creating ivars and property/synthesise. Nowadays only property/synthesise is used.One benefit I see is of less code and no confusion.
Confusion!!! Yes, if ivars and its property are of different name, it does create a confusion to other person or even to you if you are reading your own code after a while. So use one name for ivar and property.
By using property KVO/KVB/KVC are handled automatically, thats for sure.
#property/#synthesise sets your ivar to 0/nil etc.
Also helpful if your subclass contains same ivar.
For mutable objects Dont make properties.

Is there a way of specifying a selector without the #selector syntax / what is going on behind the scenes with #selector

Is #selector a convenience syntax for some sort of longer C syntax, or is it a "hard wired" part of the Objective-C language/compiler? For example, I know that when I call #property, depending on the arguments, different equivalent Objective-C code is "generated" re: getters and setters. What is going on behind the scenes with #selector? Is it specifying an Objective-C message?
#selector() is a part of the language. It specifies literal SEL just like #"" specifies a literal NSString.
It's worth understanding that #selector represents a selector, not a message. A selector is just a name. It's just one small part of a message. It doesn't even carry type information.
Also note that #property doesn't generate anything. It just promises that the object will respond to one or two selectors (the getter and the setter). There are several ways to fulfill that contract. #synthesize is just one of them. You can also manually implement the needed methods, or use #dynamic to promise that it will somehow be handled at runtime.
To answer the question in your title, NSSelectorFromString will let you create a selector from an NSString (you can also do the opposite with NSStringFromSelector), although it's more efficient to use #selector.

How does accessing ivars directly differ from using an accessor?

So in some of the codes I see, they access an objects ivar directly instead of using accessors . What are the advantages of using them instead of accessors?
So how would this
thing = object->ivar
differ from this?
thing = object.ivar
Thanks.
First let me say, I totally loathe the Objective-C dot notation. It sacrifices understandability for brevity and that is a bad thing. In fact, the other two answers here both show evidence of the kind of confusion dot notation introduces.
Having got the rant out of the way, I'll now try to answer the question.
Under the hood, Objective-C objects are implemented as pointers to C structs. This is why
obj->ivar
sometimes works. Given that it's a C struct
(*obj).ivar
should also work exactly as you would expect for C. Having said that, you can make ivars private or protected, in which case using the above outside a scope where they are visible will cause a compiler error.
The dot operator when applied to an Objective-C object (which is a pointer don't forget) has a totally different meaning. It's syntactic sugar for sending an accessor message to the object meaning that:
foo = obj.property;
obj.property = foo;
is identical in effect to
foo = [obj property];
[obj setProperty: foo];
That is all there is to dot notation. If you go through your code changing all instances of the first form to instances of the second form, you have done everything the compiler does wrt dot notation.
In particular
you do not need a declared #property to use dot notation. You can declare the set and get accessors in the traditional way as Objective C methods, although it is definitely best practice to use #property declarations for things that are logically properties.
you do not need a backing instance variable. There's no reason why your getters and setters can't calculate values.
Given the above, the major difference between obj->ivar and obj.ivar is that the former modifies the ivar directly and latter invokes an accessor, this means that the latter can do any memory management stuff needed (retains, releases, copies etc) and can also invoke key value observing.
This is one thing with a huge difference between c/c++ and objective-c.
In C/C++ the . accesses the variable directly and the -> accesses the variable if it's a pointer to the variable, so basically it is the same.
In Objective-C the . is a shortcut to access the property using the setter and getter function and it is always using those functions. You can't access ivars with it if there is no property with that name.
Some say it's "dirty" to allow direct access to the variables. If more people work on the code it's "cleaner" to use accessors because it might be easier to debug where variables are changed since you can always break in the setter.
You can even do "bad" things with it, like:
NSArray *array = [NSArray alloc] init];
int count = array.count;
array.release;
this will technically work, because the array.release is a shortcut for [array release] but it is bad style to use . for other things then properties.
The advantage of properties is that they call methods that work with your ivars, in stead of calling the ivars directly, so you can do things like this:
-(void)setFrame:(CGRect)frame
{
if([self frameIsValid:frame])
{
if(self.flipsFrames)
{
frame.size = CGSizeMake(frame.size.height,frame.size.width);
}
[super setFrame:frame];
[delegate viewSubclass:self ChangedFrameTo:frame];
}
}
Four advantages shown here are:
The possibility to override
The possibility to check a given value
The possibility to alter a given value (use with caution)
A way to react to calls
Another advantage:
-(NSInteger) amountOfMinutes
{
return amountOfSeconds * 60;
}
You can use 1 ivar for multiple properties, saving memory and preventing/reducing redundancy, while keeping useful different formats.
There's not really an advantage to using ivars, except when you don't want to use a property so your class is more encapsulated. That does not make it impossible to reach, but it makes it clear it isn't supposed to be reached.
All ivars are private. There is no way to access them directly from outside the object. Therefore, both of your code samples are equivalent, in ObjC terms.
When you call object.ivar, what you are really doing is calling object's ivar selector. This may be either a getter method that you wrote yourself, or more likely, a synthesized getter method that you created with #synthesize.
thing, however, is an ivar. Your code would be calling the ivar selector on object and assigning the result directly to your instance's thing ivar.
If you had instead written it as self.thing = object.ivar, then you would be using your instance's setter method to assign to thing.
Some of the advantages of using accessors (specifically, synthesized properties) in ObjC are KVO/KVC compliance; better concurrency support; access control (readonly, readwrite); as well as all of the advantages that accessors give you in any other OO language.