On benefits of using ivar variables instead of getters - instance-variables

Though i am using Objective-C syntax, the question language agnostic.
Assuming the following declaration
#synthesize activities = _activities;
self.activities will call the getter and _activities will check for the value which was already assigned. The main benefit of this assignment, as i understand it, is to clearly differentiate when setter is called and when local variables is called instead.
While this is nice, what is the real tangible benefit of using ivar vs using getter methods?
I can think of one, what are others?
I suppose using ivar is faster then calling the getter, but compared with what goes on with touch events, the difference is negligible.

Accessing the instance variables directly means circumventing any atomicity protection and memory management supplied by the synthesized accessors. If it's clear when you're doing that, it's easier to audit such access to ensure that you're looking after these aspects of the class's behaviour yourself.

Related

When to use #property? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should I use #properties?
When to use properties in objective C?
I have been programming in objective-c for a little over a year now, and I always felt like it was a convention to use #property and #synthesize. But what purpose do they really serve ? Are they solely there to be communicated between classes ? So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K. ?
Another question:
If I set the property of an NSMutableDictionary, it is retained, right ? So, in my class I don't have to call alloc() and init(), do I ?
What are the rules to use properties ?
But what purpose do they really serve?
Access control to iVars and abstraction between representation and underlying data.
Are they solely there to be communicated between classes?
No, they are for when you want to control access to iVars instead of accessing them directly or when you could in the future change underlying data structures but wish to keep the current representation.
So, for instance, if I use an NSMutableDictionary only in the scope of the class where it was declared, an omission is O.K.?
It depends. Do you want to have controlled access to the iVar? Would it be possible for your code to change so the dictionary is fetched and not a direct iVar. Usually, the answer is yes.
If I set the property of an NSMutableDictionary, it is retained, right?
Depends on how you declare the property.
So, in my class I don't have to call alloc() and init(), do I?
You have sloppy wording here. I think you are asking if you still need to construct an instance of a property. Yes, you will need to construct an instance of a property in some way. There are lots of ways of doing this.
NOTE: the convention for talking about methods is use their signature. Instead of alloc(), you would use -alloc.
What are the rules to use properties?
This you will need to read the doc for.
Like in another languages, when we want to make our variable global or public we use public access modifier. In objective c when we want access our another class variable in other class, we use #property and #synthesize them. Basically #synthesize is way by which compiler create a setter and getter methods for that variable. You can manually create them but not use #synthesize.
By creating object of that class you can access your property variable in other class.
By using retain, you clear that is take place memory and not exist until that container class not goes dispose or released.
Properties simply make your life easier.
Nowadays use properties as much as you can in terms of memory management, code-style and timesaving.
What do #propertys do?
They can create getter and setter methods (depends on given parameters).
Normally you declare instance variables in the header file (like in c++).
Now you simply let that be and instead of that declare the properties you want for instance variables.
Properties can get multiple arguments.
For normal objective-c objects, where you need a pointer (*) you would write.
#property (nonatomic,retain,...)
When you #synthesize it it creates a getter and a setter.
The setter automatically does stuff like releasing your old object, that your variable hold and retaining the new one.
So you don't have to do that manually (which should be quite often the case). Thats important.
You also can give it arguments (readonly,readwrite) to decide if to set a setter or not.
You can even declare a #property in the header file readonly and override that in your implementation file with a extension (a category with no name).
To dive deeper into this, read the apple developer manuals, which are quite effective.
Hope that helps a bit.
Shure it is the tip of the iceberg, but it's mostly everything you need.

Why Use Properties?

So I've been programming on Objective-C for over a year now, and I can't seem to understand the use for properties. I have searched the internet a few times but never really found a good explaniation. I understand how to create them:
#property (something, something) something *variableName;
#syntheize variableName;
But should I make all my instance variables properties. To me, from what I know, it seems like a waste of code. But when I look at code online, sometimes I see like 25 properties in one class. Which I think is a waste. The only time I ever use them is when passing info from a UITableView cell selected to a detail viewController. For that, I use:
#property (copy) NSString *myString;
Can you also explain what: nonatomic, copy, retain, assign, etc. mean.
Thanks
These properties are convenience methods for creating getters and setters.
Atmoic v Nonatomic
Assuming that you are #synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.
With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.
What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.
Assign, retain, copy
In a nutshell, assign vs retain vs copy determines how the synthesized accessors interact with the Objective-C memory management scheme:
assign is the default and simply performs a variable assignment
retain specifies the new value should be sent -retain on assignment and the old value sent release
copy specifies the new value should be sent -copy on assignment and the old value sent release.
Remember that retain is done on the created object (it increases the reference count) whereas copy creates a new object. The difference, then, is whether you want to add another retain to the object or create an entirely new object.
Properties are a good technique to expose values. You shouldn't expose all instance variables as that would break good OOP encapsulation.
Here is Apple's documentation on the matter.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html
A key point is:
Declared properties address the problems with standard accessor
methods by providing the following features:
The property declaration provides a clear, explicit specification of
how the accessor methods behave.
The compiler can synthesize accessor methods for you, according to
the specification you provide in the declaration. This means you have
less code to write and maintain.
Properties are represented syntactically as identifiers and are
scoped, so the compiler can detect use of undeclared properties.
Properties enable automatic handling of the variables. So when you do a synthesize the compiler will generate your getters and setters allowing one to do class.variableName = value (indicating that the compiler will execute [class variableName:value].
Pretty decent explanation of the properties here: http://cocoacast.com/?q=node/103
If you need getters and setters to expose some instance variables, or you want some automatic retain/release memory management or thread safe accessors, then properties are a less verbose way to automatically create these smart getters and setters. If you don't want to expose something outside an object or thread, and don't want runtime memory management (say, for some malloc'd C struct) then properties might either a waste, or syntactic sugar (which may or may not improve code readability), or put there by a coder who doesn't know the difference.
The properties is a nice feature which gives you getter and setter method automatically by synthesize and give you relief by not setting and getting the value.
A property may be declared as "readonly", and may be provided with storage semantics such as "assign", "copy" or "retain". By default, properties are considered atomic, which results in a lock preventing multiple threads from accessing them at the same time. A property can be declared as "nonatomic", which removes this lock (reference from http://en.wikipedia.org/wiki/Objective-C#Properties).

Objective-C properties - is using [self myProperty] or self.myProperty slower than myProperty?

I'm using Objective-C properties to handle retaining/releasing instance variables for me. In my class, i'm doing stuff like this:
self.myProperty = somethingIWantToRetain
[self.myProperty doSomeAction]
[self.myProperty doSomethingElse]
Is using [self myProperty] / self.myProperty slower than simply using myProperty for those lines where i'm not changing the value of myProperty? Eg would the following be faster?
self.myProperty = somethingIWantToRetain
[myProperty doSomeAction]
[myProperty doSomethingElse]
Thanks
It's almost certainly a little bit slower, but it's unlikely to matter much.
Referring to your ivar directly (with a naked myProperty) accesses the variable directly. Referring to your property getter (with the equivalent self.myProperty or [self myProperty]) has to invoke a method, which will generally perform a retain and autorelease on your ivar.
However, method dispatch in Objective-C is very, very fast, and the retain/autorelease calls are pretty cheap as well, especially for objects that will likely not be destroyed when the autorelease pool is cleared. I would focus on readability and consistent style, and only worry about performance here when it becomes clear that you have performance bottlenecks to chase.
To be precise, when you write [myProperty doSomeAction], you are not actually accessing the property, but accessing the instance variable (used as the backing variable of the property) directly.
You only access the property (thru its setter and getter) with the dot-notation [self.myProperty doSomeAction] (or by calling the setter/getter explicitly like [[self myProperty] doSomeAction] which is an exact equivalent, as this is what the compiler translates to when compiling your code)
So when you write [myProperty doSomeAction], as it access the variable directly — contrary to [self.myProperty doSomeAction] which calls the getter of myProperty thus making an additional method call / message send — then yes in theory it will be faster as you will gain one message dispatch.
But in practice you won't see any improvement, so there is no need to consider accessing the variable directly (and it will make you loose flexibility if you want to implement it another way later)
Moreover, if you use the Modern Runtime (which is the case if you code for any version of iOS, Legacy Runtime being only used in 32-bits Mac OSX), then explicitly defining the backing variable for the property is not needed anymore. Thus you can declare the #property in the .h and #synthesize it in the .m without any instance variable (the compiler will generate it for you at compile time), and in such case you won't be able to call the (non-existing) instance variable! (at least not before the #synthesize directive)
Using Objective-C 2.0 dot syntax is equivalent to calling the getter, so the first snippet would be slower on the basis that you'll incur two additional dynamic dispatches.
That being said, the loss will be minor and obviously you'll gain the flexibility of being able to change the setter and getter at a later date (such as if you end up making that value implicit such that it's not technically stored in memory, or passing it off to a third object, or doing something asynchronous to store that may require you to block on the getter in some circumstances).
Slower as in one more step in operation? Yes.
Slower as in noticeably or realistically slower? Absolutely not.
You have to remember that modern cpus run programs at several million operations per second. In virtually all languages, calling a getter method is essentially the same speed as accessing the ivar itself (especially when there's no other code in the getter method).
It's good habit to use getters rather than accessing the ivars directly though, so I wouldn't try to "speed things up" by ignoring them.
Yes, it would be marginally faster, but it's unlikely that you'll improve performance noticeably by doing this kind of micro optimization. If you use self.myProperty, you could later decide to implement a different accessor method without having to change your code everywhere.

How can I avoid redundancy while declaring new class attributes in Objective-C?

In my code, every time I need a new object attribute for my class, I typically copy/paste its name in 4 different places!
The declaration in the header file (NSObject * myObject;)
The #property() line
The #synthesize() line in the implementation
Releasing it under dealloc: (only for objects of course)
I do this because it works, not because I completely understand what's going on. I do know that the declaration in the header file allows other classes to see its attributes, the property specifier determines how its getter/setter methods will be constructed. And the synthesize line actually builds those getter/setter methods. I also know that primitive types should use (nonatomic,assign) instead of (nonatomic,retain), but I have no clue when I should omit the nonatomic.
What can I do to avoid redundancy in my code. If I change or add a variable in my class I have to check 4 different places, and it gets old really fast. Are there any key strokes to make this process faster? Are there lines of code I can simplify or combine to obtain the same result?
Accessorizer will automate a lot of this for you.
In the latest version of Clang (Ships with XCode 4, not in XCode 3 yet) you get default #synthesize as well as default ivar creation. The default ivar creation already works, but not on the simulator. With both of these features all you need to do is add the #property line and deal with the memory management in dealloc
As far as nonatomic vs atomic. atomic is the default, and what happens when you leave off the nonatomic annotation. Atomic guarantees that the value is completely set before allowing anything to access it, nonatomic doesn't. Atomic is only useful in threading situations, and is slightly slower in singlethreaded applications.
It's important to understand what each of those lines of code does. They are not all the same and they are not necessarily redundant. One thing that will help is to use the correct terminology — for example, with NSObject *myObject; you're probably referring to an instance variable declaration.
First and foremost, a #property declaration in an #interface lets you say that instances of a class expose a piece of state. It doesn't say much about the implementation of that state, only that it's exposed by instances of your class and the API contract (memory management, atomicity, methods) for the state.
The #synthesize directive tells the compiler to create or use a specific instance variable as storage for a declared #property. This does not need to be how you provide storage for a property. For example, Core Data provides its own storage for modeled properties, so you use #dynamic for those instead. You also don't need to use an instance variable with the same name as your #property — to extend your example above, you might name your instance variable myObject_ while naming your property object and that's perfectly fine.
Finally, you send the instance variable -release in -dealloc — for an object-type property marked retain or copy — because you've said you'll manage its memory. You're not releasing the property, you're releasing the storage. If you implemented the storage some other way, you'd clean it up some other way.

Does it make a difference in performance if I use self.fooBar instead of fooBar?

Note: I know exactly what a property is. This question is about performance.
Using self.fooBar for READ access seems a waste of time for me. Unnecessary Objective-C messaging is going on. The getters typically simply pass along the ivar, so as long as it's pretty sure there will be no reasonable getter method written, I think it's perfectly fine to bypass this heavy guy.
Objective-C messaging is about 20 times slower than direct calls. So if there is some high-performance-high-frequency code with hundreds of properties in use, maybe it does help a lot to avoid unnessessary objective-c messaging?
Or am I wasting my time thinking about this?
This kind of premature optimization should really be postponed until you actually notice or measure (with Instruments.app) a real problem.
No offence, but you're probably wasting your time thinking about it. Unless you have code that accesses that property thousands of times a second, then you're not going to see any performance differences.
The two aren't really interchangeable (ok some of the times they are). Access the ivar directly when that is what you need and use the accessor methods when that is what you need. It will probably depend on the the class hierarchy, the implementation of the class, is the code thread safe etc, etc.
All things that are largely upto you if it's your code. Might someone want to subclass this class and write a custom implementation of -foobar that always returned #"BOO" but they find that the superClass method -printFooBar now prints #"hello darling" because it prints out the value of the variable foobar instead of the value returned from self.foobar ?
Calling the accessor method does have more overhead than using the variable directly, but there are more things to consider than performance. Personally i find the position "always use the accessor method" just as ridiculous as saying "never use the accessor methods" - which would clearly be ridiculous.
Yes using property getters are much slower than direct access. A property getter is useful outside of the self class (and categories) for encapsulation, but I see no benefits using a self.ivar getter, unless you have overridden the getter to something else.
(And why are you using self.ivar in the first place?)
The only cases where self.ivar will be different from self->ivar are:
The property is atomic, so self.ivar will be similar to
spin_lock(&ivar_lock);
id retval = [ivar retain];
spin_unlock(&ivar_lock);
return [retval autorelease];
for an id property, and
spin_lock(&ivar_lock);
spin_lock(&destination_lock);
memcpy(&destination, &ivar, sizeof(ivar));
spin_unlock(&ivar_lock);
spin_unlock(&destination_lock);
for a struct. There is no difference between the two when the property is nonatomic.
When the class is not final. A category of the class or a subclass can override the property getter to something else. But I think overriding a concrete property is not a good style.
Like what the others have said, unless you have tested that the getter is a hot spot, changing it back to direct ivar access won't help much.
Some may disagree, but I happen to like accessing the ivar directly and bypassing the whole messaging business where possible. I think it makes my intentions clearer, since if I ever need to message the getter (for memory management or the like), then I will.
It's a tiny bit less efficient, but you still should generally not make your object state public. Although public members are considered bad in most OO languages, there's actually a pragmatic reason why in Objective-C: The framework uses your "getter" and "setter" methods to make certain things automatic, such as memory management and KVO notifications. With ivars accessed from multiple places, every piece of client code needs to fully understand all the responsibilities that the accessor methods were taking on and perform those duties in the exact same way itself.
So it's no "absolutely don't access your own ivars," but just make sure you fully understand what it entails in a given situation.