does objective-c methods support "pass by value"? - iphone

Does objective-c methods support "pass by value"? Or perhaps to be more specific:
Is the default behavior for parameters passed into a method pass-by-reference?
If yes, are there any variations from this in some circumstances - for example if the parameter is just a basic int as opposed to an object? (or is this not relevant in objective-c)
Is there anyway to have a method support pass-by-value for a basic variable such as int?
Is there anyway to have a method support pass-by-value for an object? (I'm assuming no here, but for completeness will ask. Of course one could within the message do the copy yourself, however for this approach I'll consider this not to be something objective-c methods offers you, i.e. rather it was a do-it-yourself)
thanks

Objective-C does not support references, at least not in the C++ sense of the term.
All Objective-C objects are allocated on the heap, and therefore all "object variables" must in fact be pointer types. Whether a pointer can be considered to be effectively the equivalent of a reference is open to debate. When talking C++ for example, there are clear semantic differences (otherwise, what's the point...)
So to answer your questions:
No, Objective-C only supports pass-by-value. If you pass an object pointer to a method, you pass the pointer by value - you are not passing a reference.
There is no inherent difference between objects and primitives in this regard, apart from the fact that objects are always referred to by pointer, never by value. You can pass a primitive type pointer in if you like.
Yes. This is always the case. Again, if you pass in a pointer to a primitive, you are passing a pointer by value, not a reference.
You're pretty much bang on the mark with this one, other than the fact that you're passing around pointers, not references.

No. It's pass-by-value by default, like in C. Except for the fact that for the Objective C class instance references, the value is a reference. So Objective C class instances are passed effectively by reference.
N/A
See 1.
Not really. You can serialize, pass the string, and recreate inside. Or you can have the object store its ivars as a structure and pass that structure by value. Some objects support cloning.

Related

Objective C convention: When to use For and when to use With

According to the Apple guideline , seems it is confusing, e.g. for method viewWithTag
In Java, I would have a method called
getViewByTag // Java version, equivalent to viewWithTag in Obj-C
But I also found there are some method like objectForKey, so why not just use objectWithKey instead?
getObjectByKey or just get // Java version, equivalent to objectForKey,
// but why not objectWithKey? Or not viewForKey above?
I actually think it is much simpler than what most answers think. I think it has less to do with complex programming language specifics, and has more to do with the uniqueness of the object in question.
When you say viewWithTag:, you are asking the UIView for any view that has that tag. There might be several. The UIView will return one of 'em.
However, objectForKey: (to me) sounds like there should be a single object (or nil) associated with that key. So, the key kinda exists and is bound (tightly coupled) to a single object.
EDIT:
There is an answer mentioning the existence of "by", which further implies how the convention has nothing to do with programming language complexities. It's just natural English.
NSString's stringByAppendingString:, for example, uses by, only because the function is written with a the verb appending. You can't say withAppending, that's bad English.
From my observation
While setting/getting the objects, you use WITH.
e.g. For setting of NSMutableArray object
- (id)initWithCapacity:(NSUInteger)numItems
While setting/getting the properties for objects, you use FOR.
e.g.For setting value for property of type NSMutableDictionary
- (void)setValue:(id)value forKey:(NSString *)key
Hope this helps in clearing your doubt
It seems like with is used for properties that directly belongs to an object. A UIView has a tag property so viewWithTag:14 could be rephrased as "Find the view whose tag property is 14".
When you put an object in a dictionary, associated to a key, this key is not necessarily part of the object itself. objectForKey:#"foo" is a way to say "Look for an object that's linked to the key "foo".
The Apple guidelines do not make any such claims as to when to use for or with. The point of the coding convention is to indicate what the types of the arguments may be and to write method signatures which are natural sounding.
The reason for the for or with in the method name is to identify the type or purpose of the first parameter to the method, which helps it read better.
Apple itself uses several conventions but that is the basic purpose, there is no concrete right or wrong just try to identify the first parameter of the method in the method name with either for or with.
And as for Apple conventions - get(whatever) is not even part of the actual conventions, so you could ask when do I use get or not.
Read this http://cocoadevcentral.com/articles/000082.php
also dont forget (by) NSURL urlByAppendingPathComponent etc - get a feel for it and you wont go wrong
You use "with" whenever the parameter is owned or to be owned, or will be a relatively permanent attribute by the object to the left of the "with" word.
initWithCapacity / arrayWithCapacity - the capacity will be an attribute of the container object being called and will be relatively permanent (until you add objects to it beyond the initial capacity)
viewWithTag – return a view "having" the specified "tag" attribute.
Whereas you use "for" to denote a looser association between the "desired" object and a "token" object that you use to get to it.
- objectForKey / attributeForValue – usually the "object" does not own the key.
- documentForWindow – the window is owned by the window controller and not the document. Furthermore there could be more than one window for each document.
But for looser associations of multiple
objects of the same type within a single method call, it's customary that you use something like:
doSomethingForFoo:withThisOtherFoo:havingYetAnotherFoo:
So the order for such complex call is:
for
with
having

When should i use assign in Objective c?

I understand the reason i should use retain, but why should I ever use assign? (besides to avoid retain cycles)
[EDIT]
So if i understand Chuck's answer on https://stackoverflow.com/questions... correctly, when ever I use assign, the variable would lose scope once it gets out of scope of the method just like it does in regular C-type language behavior?
You should assign things that aren't objects. Any C type (such as int, float, char, double, struct, and enum) should be assigned.
Few examples I can think of:
It is not an object. Such as BOOL, int
Most of the times delegate properties are assigned (to prevent cycles)
Anything that is not an object
Delegates
IBOutlets that are not top level (i.e. subviews since those are already retained by the view)
Assuming that Chuck's answer from the linked question is correct, there's not really a "scope" in Objective-C. Sounds like you should just use assign for any primitives, like ints or BOOLs. Anything that you need to have ownership of, use retain (or other commands, as Chuck describes).

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).

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.

Storing a C struct in CFMutableDictionary

Since there is no counterpart to NSValue in Core Foundation, how are we supposed to store C structs in a CFMutableDictionary?
First, you can put an NSvalue in a CFMutableDictionary as-is, so the answer is "use NSValue." But I assume the rest of your question is "without using any Cocoa objects." In that case, just create a non-retaining CFMutableDictionary, and you can put any pointer you want into it. See "Defining Custom Collection Callbacks" for some example code. I use these a lot.
Remember that these still have to be pointers, so you're going to have to allocate your structs on the heap, not the stack. And that means that memory management is now your problem. Of course you could create a custom set of callbacks that do whatever you want, so if you're using boost or something else with its own ref-counting system, you can still implement that with CFMutableDictionary.
And of course you can replace the struct with a small data object. That's usually a lot easier. But different problems need different solutions.
CFMutableDictionary
CFDictionaryAddValue
A CFType object or a pointer value to add to the dictionary.
you just pass a pointer to your struct.