No ivars -> What am I missing? - objective-c

I never use ivars. I only use properties -- sometimes assign properties with primitive types, and sometimes on a "private" class extension. I've seen the advantages of not using ivars in switching to ARC -- I have some borrowed code with lots of ivars that I still can't "ARC", since I don't know what needs to be retained. So I know some advantages of not using ivars, but what are the advantages of using ivars instead of properties?
Note: I depend exclusively on the ivars that are automagically added in (by the compiler?) for the property declaration.
Don't mark to close: I've looked at some of the other questions, like this and this and none hit the spot. The titles look good, but like so many questions on SO, the questions are a mess of strange doubts and other stuff.

Declared properties cannot be treated in the same manner as an #protected ivar. You can declare the property in a class extension to keep it private from any other class, or declare it in the header interface to make it publicly accessible, however there is no way to make it accessible only to subclasses. This would require the ivar declaration.
EDIT
Just another brief thought. I have recently been writing a lot of framework classes, and I think there might be something to be said for using iVars as documentation.
For example, let's say you are calling some code in a tight loop and you want to ensure that it is performant. Inside that tight loop you want to access a property of a class, but need to know whether each time you call it the return value is calculated on-the-fly or stored in an iVar. Seeing the iVar in the header is a quick way to ensure that you'll get that variable back without much overhead.

I don't see any reason to use iVars if you don't have to. If Apple and the compiler want to do work for you, I say let them. You'll have code that more efficient and easier to maintain. At this point iVars are legacy code.

One good reason for me: an annoying GCC bug, see this other question for a description.
If you're using Clang/LVVM, then you don't have to worry about this bug.

Related

Case for not using Properties in Objective-C

In the apple OS X 10.8 Core Library Documentation under Programming with Objective-C, it states,
"It's best practice to use a property on an object any time you need to
keep track of a value or another object. If you do need to define
your own instance variables without declaring a property, you can add
them inside braces at the top of the class interface or
implementation..."
So I'm curious, then, what are going to be the cases where you need to define instance variables without declaring properties? Aside from what apple says, could it really just be a personal preference thing?
Thanks!
Some of it is definitely a matter of preference, but not everything: you are better off with a property for items with external visibility, and items that need different access control inside vs. outside your class. The issue has been much less pronounced since the introduction of ARC, because before it you may wanted to use properties for automated calls of retain and release. The significance of this aspect of properties has been reduced greatly to situations when you need to automatically copy the objects into your property.
If you're using ARC and a recent runtime (recent enough to let you declare your ivars in your #implementation block), then instance variables are suddenly awesome again. Why? Because unlike #properties they're class-specific. No risk they'll accidentally be overridden by a subclass.
They're also faster in the simple case, since you don't call any methods to get or set them.
I personally also find it much cleaner. No more class extensions defining private #properties, and all that junk. Just ivars, nice and simple.
So the best advice, IMHO, is to use them by default. Only use #properties if you actually need their functionality, e.g.:
You need a way to access them from outside your class.
You want to allow subclasses to override them.
Your getter or setter is more than just a trivial assignment.
The latter two are all actually rarer than you might think. It's generally unwise to try to override properties in subclasses, just because it's a little unusual and there are some rough edges.
If you do find, later, that you need to upgrade an ivar to a #property, it's nice and easy - the only place it can be accessed is in your #implementation, so it's generally a simple search-and-replace to add "self." to its references (and maybe remove the leading underscore, if you name them that way). 'til then you needn't pay the cost and run the risks of using #properties.
I prefer properties because I am able to define setters/getters and because I like more that syntax.
Many people affirm that is a bad practice to use ivars, like in this article:
http://cocoasamurai.blogspot.it/2012/08/cover-up-those-ivars.html
Unfortunately nowadays programmers call bad practice all what they don't like, even without objective reasons.
If you declare an ivar you still can use the #private directive, so isn't a matter of exposing or not variables.I think that if you like more ivars you should use them.

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.

Objective-C class without properties?

I'm in the process of looking over some code in a large project, and I have noticed that in several of the classes, instance variables are created but no corresponding properties (#property) are created.
Is it "wrong" to create instance variables without properties? Doesn't this become a memory management issue?
I've actually never seen code like this before so I'm not sure what to think at this point.
Thanks in advance!
#properties are merely shorthand -- very convenient short-hand -- for code you can write yourself, no magic about it.
It may also be that the #properties are declared in the implementation file within a class extension and there is no publicly accessible API for directly manipulating the instance variables.
There's no reason that you have to use the Objective-C 2 style setters/getters to manage your instance variables - as long as the instance variable is released within the dealloc method (if indeed it's a alloced/inited object, etc.) then there's nothing to worry about.
Bear in mind that prior to Objective-C, such properties (and the whole #property/#synthesize syntax) simply didn't exist, so you had to create your own getters/setters if you deemed it necessary/convenient.
Not at all. Instance variables work fine, and are subject to the same memory management rules as anything else: retain it before saving it to the instance var, and make sure you release it when you don't need it anymore (typically in the dealloc).
Some history here might be helpful:
In the beginning, there were only instance variables. "Properties" existed only in an informal way, by convention, for objects outside your class to access "public" data that the class exposed. You'd write your own -(Foo *)foo and -(void)setFoo:(Foo *)f methods for each of these. Those often were like boilerplate code, trivially returning the ivar in the first case, and doing the right retain/release/set dance in the latter.
So Objective-C 2.0 came along and gave us the ability to declare properties with the language syntax, and even generate the accessors for us-- lots of time and boilerplate code was saved.
As time went on, some people began to think about all ivars as "properties", public or private. The public ones appear in the .h file as #properties, but you can also create a private interface to your object in the .m file that declare your "private" #properties, so you can use the accessors inside your class. This might or might not be overkill, depending on your philosophy to it, but this I think has to the situation you see now, where naked ivars look suspicious.
They shouldn't. Instance variables happily exist without any of the other machinery. Just get your retain/release right (in non-GC runtimes).
As you get more advanced, see #bbum's answer to this question:
Must every ivar be a property?
for some more varsity things to think about around the benefits of properties around KVO and subclassing.
Properties for instance variables aren't mandatory. In fact, prior to v2.0 of Objective-C, there was no such thing as properties -- you had to write your own accessors and mutators for instance variables (if you wanted to access them outside of the class). Properties can simplify memory management, but to be honest, memory management of ivars isn't that difficult, and it's not hard to handle yourself.

What's the harm of property override in Objective-C?

There are several situations where you might override a super class's property.
You declare a property with the same name and same attribute of its
superclass'.(since if you change the
attribute you can get an compiler
warning).And you can synthesieze
with an ivar that you create. What's
the use of this? Or what's the harm
can it do?
If a superclass declares a property in a class extension (a category
with no name), then it might not be
in the header file. If you don't
know that property from the header
file, you can declare the same name
property with what ever attribute or
class you want. But the
setter/getter method will override
the ones for that "secret property".
I think this can only do harm. But
since you don't know from the header
file, how can you avoid this?
You can declare a property in the header file as "readonly" and in
class extension redeclare it as
"readwrite". I think this is the
situation that it can do good.
Is my understanding about these situations right? And I don't know what good the first and second situations can do. But if I want to avoid the first situation, I can check if the subclass already has the property before I declare it. But if the property is not in the public header file, as in the second situation, I just don't know what to do.
There is a proper place for each of the situations you have mentioned, with varying frequency of use out in the wild. You just have to use care not to step on yourself. I'll illustrate with example's I have personally come across.
Subclassing to intentionally override a property
In this situation, like Joe mentioned, you had better know exactly what you're doing and have no other options before you override a property. I've personally found it's usually sufficient to override a single setter or getter for an already existing property to achieve customization, rather than re-declare and synthesize the property. For example, consider a specialized UIView subclass that only makes sense to have a UIClearColor background. To enforce this, you may override -setBackgroundColor: to just print a warning message and then not call super's implementation. I'll say I've never had a reason to completely override a property, but I won't say it couldn't be a useful tool in some case where you need to completely hijack an existing property.
Private Property
This is more useful than you give it credit for. The alternative to a private property is a plain ol' ivar, which we're all familiar with. If this is an ivar that's changing with some frequency, you'll end up with chunks of code that look like this:
[_myIvar release], _myIvar = nil;
or:
[_myIvar release];
_myIvar = [someValue retain];
While it doesn't look too bad, memory management boilerplate code like this gets really old, really fast. Alternatively, we could implement the above example as a private property, with retain semantics. This means, no matter what, we just have to:
self.myIvar = someValue;
Which is much easier on the eyes and fingers after awhile. You're correct in noting that, since this property is invisible to the rest of the universe, it could accidentally be overridden by a subclass. This is an inherent risk when developing in Objective-C, but you can take measures to make the risk vanishingly small. These measures are variations on modifying the name of your private properties in a predictable manner. There are infinite roads you could take here: say, for example, you make it a personal policy to prepend your private property names with your initials and an underscore. For me, I would get something like mw_ivar, and corresponding -setMW_ivar: and -mw_ivar accessors. Yes, it's is statistically possible that someone could come along and accidentally override that name, but really, they won't. Especially if you have a way of publishing your practices to those who may use your code. And, I can safely say that Apple has not gone around and made private properties that were mangled in such a way, so you'll be safe on that front as well.
Publicly Readonly, Privately Readwrite
This is just standard practice. You're right that it's useful, and also that it's not dangerous since the property is in the header. Anyone accidentally overriding it has only themselves to blame.
Good question
The use of this is you as the
developer should know what you are
doing at this point and need to add
customizations to the base class
property. And since you know what
you are doing you will properly call
the supers implementation unless
you have good reason not to. The
decision not call super could be
harmful especially in situations
where you do not know how the base
class is implemented.
Yes this is harmful but can be
avoided by not over using categories
and carefully choosing a name of
properties or methods and consider
prefixing them.
Yes you are correct that is good for
limiting access to your property.
Example for #2
#interface UIView(PFXextended)
-(NSArray*)PFXGetSubviewsOfType:(Class)class;
#end

Should I use properties or direct reference when accessing instance variables internally?

Say I have a class like this:
#interface MyAwesomeClass : NSObject
{
#private
NSString *thing1;
NSString *thing2;
}
#property (retain) NSString *thing1;
#property (retain) NSString *thing2;
#end
#implementation MyAwesomeClass
#synthesize thing1, thing1;
#end
When accessing thing1 and thing2 internally (i.e, within the implementation of MyAwesomeClass), is it better to use the property, or just reference the instance variable directly (assuming cases in which we do not do any work in a "custom" access or mutator, i.e., we just set and get the variable). Pre-Objective C 2.0, we usually just access the ivars directly, but what's the usual coding style/best practice now? And does this recommendation change if an instance variable/property is private and not accessible outside of the class at all? Should you create a property for every ivar, even if they're private, or only for public-facing data? What if my app doesn't use key-value coding features (since KVC only fires for property access)?
I'm interested in looking beyond the low-level technical details. For example, given (sub-optimal) code like:
#interface MyAwesomeClass : NSObject
{
id myObj;
}
#proprety id myObj;
#end
#implementation MyAwesomeClass
#synthesize myObj;
#end
I know that myObj = anotherObject is functionally the same as self.myObj = anotherObj.
But properties aren't merely fancy syntax for instructing the compiler to write accessors and mutators for you, of course; they're also a way to better encapsulate data, i.e., you can change the internal implementation of the class without rewriting classes that rely on those properties. I'm interested in answers that address the importance of this encapsulation issue when dealing with the class's own internal code. Furthermore, properly-written properties can fire KVC notifications, but direct ivar access won't; does this matter if my app isn't utilizing KVC features now, just in case it might in the future?
If you spend time on the cocoa-dev mailing list, you'll find that this is a very contentious topic.
Some people think ivars should only ever be used internally and that properties should never (or rarely) be used except externally. There are various concerns with KVO notifications and accessor side effects.
Some people think that you should always (or mostly) use properties instead of ivars. The main advantage here is that your memory management is well contained inside of accessor methods instead of strewn across your implementation logic. The KVO notifications and accessor side effects can be overcome by creating separate properties that point to the same ivar.
Looking at Apple's sample code will reveal that they are all over the place on this topic. Some samples use properties internally, some use ivars.
I would say, in general, that this is a matter of taste and that there is no right way to do it. I myself use a mix of both styles.
I don't think any way is 'better'. You see both styles in common use, so there isn't even a usual/best practice now. In my experience, the style used has very little impact on how well I digest some implementation file I am looking. You certainly want to be comfortable with both styles (and any in between) when looking at other people's code.
Using a property for every internal ivar might be going slightly overboard, in terms of maintenance. I've done it, and it added a non-trivial amount of work that I don't think paid off for me. But if you have a strong desire/OCD for seeing consistent code like self.var everywhere, and you have it in the back of your mind every time you look at a class, then use it. Don't discount the effect that a nagging feeling can have on productivity.
Exceptions- Obviously, for custom getters (e.g. lazy creation), you don't have much of a choice. Also, I do create and use a property for internal setters when it makes it more convenient (e.g. setting objects with ownership semantics).
"just in case", "might" is not be a compelling reason to do something without more data, since the time required to implement it is non-zero. A better question might be, what is the probability that all the private ivars in some class will require KVC notifications in the future, but not now? For most of my own classes, the answer is exceedingly low, so I now avoid a hard rule about creating properties for every private ivar.
I've found that when dealing with internal implementations, I quickly get a good handle on how each ivar should be accessed regardless.
If you are interested, my own approach is this:
Reading ivars: Direct access, unless there is a custom getter (e.g. lazy creation)
Writing ivars: Directly in alloc/dealloc. Elsewhere, through a private property if one exists.
The only difference in an assignment of thing1 = something; and self.thing1 = something; is that if you want to have the property assignment operation (retain, copy, etc), done on the assigned object, then you need to use a property. Assigning without properties will effectively be just that, assigning a reference to the provided object.
I think that defining a property for internal data is unnecessary. Only define properties for ivars that will be accessed often and need specific mutator behavior.
If thing1 is used with KVO it is a good idea to use self.thing1= when you set it. If thing1 is #public, then it is best to assume that someone someday will sometime want to use it with KVO.
If thing1 has complex set semantics that you don't want to repeat everywhere you set it (for example retain, or non-nonatomic) then use through self.thing1= is a good idea.
If benchmarking shows that calling setThing1: is taking significant time then you might want to think about ways to set it without use of self.thing1= -- maybe note that it can not be KVO'ed, or see if manually implementing KVO is better (for example if you set it 3000 times in a loop somewhere, you might be able to set it via self->thing1 3000 times, and make 2 KVO calls about the value being about to change and having changed).
That leaves the case of a trivial setter on a private variable where you know you aren't using KVO. At that point it stops being a technical issue, and falls under code style. At least as long as the accessor doesn't show up as a bottleneck in the profiler. I tend to use direct ivar access at that point (unless I think I will KVO that value in the future, or might want to make it public and thus think others may want to KVO it).
However when I set things with direct ivar access I try to only do it via self->thing1=, that makes it a lot simpler to find them all and change them if I ever find the need to use KVO, or to make it public, or to make a more complex accessor.
Other things mentioned here are all right on. A few things that the other answers missed are:
First, always keep in mind the implications of accessors/mutators being virtual (as all Objective-C methods are.) In general, it's been said that one should avoid calling virtual methods in init and dealloc, because you don't know what a subclass will do that could mess you up. For this reason, I generally try to access the iVars directly in init and dealloc, and access them through the accessor/mutators everywhere else. On the other hand, if you don't consistently use the accessors in all other places, subclasses that override them may be impacted.
Relatedly, atomicity guarantees of properties (i.e. your #properties are declared atomic) can't be maintained for anyone if you're accessing the iVar directly anywhere outside of init & dealloc. If you needed something to be atomic, don't throw away the atomicity by accessing the iVar directly. Similarly, if you don't need those guarantees, declare your property nonatomic (for performance.)
This also relates to the KVO issue. In init, no one can possibly be observing you yet (legitimately), and in dealloc, any remaining observer has a stale unretained (i.e. bogus) reference. The same reasoning also applies to the atomicity guarantees of properties. (i.e. how would concurrent accesses happen before init returns and accesses that happen during dealloc are inherently errors.)
If you mix and match direct and accessor/mutator use, you risk running afoul of not only KVO and atomicity, but of subclassers as well.