Objective-c -> Structure Operator [duplicate] - iphone

This question already has answers here:
Dot (".") operator and arrow ("->") operator use in C vs. Objective-C
(5 answers)
Closed 9 years ago.
While reading some tutorials i found for the first time the "structure operator", I read that it's used to refer of an instace variable.
-(void)setNumber:(int)n{
self.number = n;
}
-(void)setNumber:(int)n{
self->number = n;
}
My doubt is: what it doing exactely? When do i use it? Why should i prefer it to the dot notation?

Dot syntax in Objective-C is just syntactic sugar which is replaced by the compiler with a method invocation. -> dereferences the pointer and accesses the member directly, with no method invocation.
In an Objective-C method call, you don't need to say self->foo, if your class has an instance variable named foo the compiler will infer the self-> portion of it. Because of this, while it's not completely unheard of, uses of -> with an Objective-C object are comparatively rare.

The arrow -> operator accesses instance variables directly, which you don't want in general, since it violates encapsulation and circumvents accessor methods (that can be a potential source of problems, like KVO not working or some desired side effects not taking place).
Instead, you should almost always use ., because it accesses the properties using getters and setters.

Related

What is the difference in atomic_load() and assignment?

I am working on a project that deals with lots of atomic operations. Till now I didn’t knew about atomic_load() and was only relying on assignment operator to get value of an atomic type and I haven’t seen an error except of so much of testing. Those atomic types are changed by multiple processes and threads as well by atomic_compare_exchange_strong_explicit(), so they will need an old value every time, and that’s where I always did oldValue = <Atomic_ type_variable> and it always works fine.
Is that just by chance? Should I prefer using atomic_load()?
foo = atomic_var is just a shortcut syntax for foo = atomic_load(&atomic_var);
Which itself is a shortcut for foo = atomic_load_explicit(&atomic_var, memory_order_seq_cst); That has a use-case when you want to use an ordering weaker than the default seq_cst.
The main reason for using atomic_load explicitly in your source code is probably to remind human readers that a variable or pointer is atomic. Or maybe as a part of a macro, using atomic_load(&(macro_input)) would create a compile-time error for a non-atomic pointer.
As a "generic" function, you can't take a normal function-pointer to it.
Its existence may be just to make it easier to write the language standard, and explain everything in terms of functions.
It's not the actual assignment that's key here, it's evaluating the atomic variable in an rvalue context (reading it's value as part of an expression, like you typically find on the right-hand side of an =). printf("%d\n", my_atomic_var); is also equivalent to atomic_load.
And BTW, the same thing holds for atomic_var = foo; being exactly the same as atomic_store_explicit with mo_seq_cst. Here it is assignment that's key.
Other kinds of lvalue references to an atomic variable are different, like read-modify-write atomic_var++ is equivalent to atomic_fetch_add.

Documentation comment for loop variable in Xcode

I know that we can use
/// index variable
var i = 0
as a documentation comment for a single variable.
How can we do the same for a loop variable?
The following does not work:
var array = [0]
/// index variable
for i in array.indices {
// ...
}
or
var array = [0]
for /** index variable */ i in array.indices {
// ...
}
Background:
The reason why I don’t use "good" variable names is that I’m implementing a numerical algorithm which is derived using mathematical notation. It has in this case only single letter variable names. In order to better see the connection between the derivation and the implementation I use the same variable names.
Now I want to comment on the variables in code.
The use of /// is primarily intended for use of documenting the API of of a class, struct, etc. in Swift.
So if used before a class, func, a var/let in a class/struct, etc. you are attaching documentation to that code aspect that Xcode understands how to show inline. It doesn’t know how to pickup that information for things inside of function since at this time that is not the intention of /// (it may work for simple var/let but not likely fully on purpose).
Instead use a simple // code comment for the benefit of any those working in the code however avoid over documenting the code since good code is likely fairly self explaining to anyone versed in the language and adding unneeded documentations can get in the way of just reading the code.
This is a good reference for code documentation in Swift at this time Swift Documentation
I woud strongly push back on something like this if I saw it in a PR. i is a massively well adopted "term of art" for loop indices. Generally, if your variable declaration name needs to be commented, you need a better variable name. There are some exceptions, such as when it stores data with complicated uses/invariants that can't be captured in a better way in a type system.
I think commenting is one area that beginners get wrong, mainly from being misled by teachers or by not yet fully understanding the purpose of comments. Comments don't exist to create an english based, psuedo-programming language in which your entire app will be duplicated. Understanding the programming language is a minimal expectation out of contributors to a project. Absolutely no comments should be explaining programming language features. E.g. var x: Int = 0 // declares a new mutable variable called x, to the Int value 0, with the exception of tutorials for learning Swift.
Commenting in this manner might seem like it's helpful, because you could argue it explains things for beginners. That may be the case, but it's suffocating for all other readers. Imagine if novel had to define all the English words they used.
Instead, the goal of documentation to explain the purpose and the use of things. To answer such questions as:
Why did you implement something this way, and not another way?
What purpose does this method serve?
When will this method of my delegate be called?
Case Study: Equatable
For a good example, take a look at the documentation of Equatable
Some things to notice:
It's written for an audience of Swift developers. It uses many things, which it does not explain such as, arrays, strings, constants, variable declaration, assignment, if statements, method calls (such as Array.contains(_:)), string interpolation, the print function.
It explains the general purpose of this protocol.
It explains how to use this protocol
It explains how you can adopt this protocol for your own use
It documents contractual requirements that cannot be enforced by the type system.
Since equality between instances of Equatable types is an equivalence relation, any of your custom types that conform to Equatable must satisfy three conditions, for any values a, b, and c:
a == a is always true (Reflexivity)
a == b implies b == a (Symmetry)
a == b and b == c implies a == c (Transitivity)
It explains possible misconceptions about the protocol ("Equality is Separate From Identity")

What is `Something#A` in scala [duplicate]

This question already has answers here:
What does the `#` operator mean in Scala?
(4 answers)
Closed 5 years ago.
I found the following syntax in Scala. I have never seen # and couldn't find much information about it? What does # mean?
case class WithRole(role: Role) extends Authorization[User, DefaultEnv#A]
It's one of way in scala to refer a type. I quote from Scala in Depth:
Types within Scala are referred to via two mechanisms: the hash ( #) and dot ( .)
operators. The dot operator can be thought of doing the same for types as it does for
members of an object. It refers to a type found on a specific object instance. This is
known as a path-dependent type. When a method is defined using the dot operator
to a particular type, that type is bound to a specific instance of the object. This means
that you can’t use a type from a different object, of the same class, to satisfy any type
constraints made using the dot operator. The best way to think of this is that there’s a
path of specific object instances connected by the dot operator. For a variable to
match your type, it must follow the same object instance path. You can see an exam-
ple of this later.
The hash operator ( # ) is a looser restriction than the dot operator. It’s known as a
type projection, which is a means of referring to a nested type without requiring a
path of object instances. This means that you can reference a nested type as if it
weren’t nested.

iPhone - difference between these two lines of code

What is the diffrence between these two lines of code:
[cmController currentPageNo];
self.cmController.currentPageNo;
There is actually a functional difference - the second line is equivalent to:
[[self cmController] currentPageNo];
Using the -cmController property getter method to access the cmController ivar may have behaviours that make it different to accessing the ivar directly. These might include lazy initialisation or atomic thread locking, or a range of other behaviours. Unless you have a good reason to, you should (in general) use the accessor methods for properties, rather than accessing ivars directly.
So to clarify:
[cmController currentPageNo]; // 1
cmController.currentPageNo; // 2
[[self cmController] currentPageNo]; // 3
self.cmController.currentPageNo; // 4
1 and 2 are functionally identical to each other, but use different syntax. 3 and 4 are also functionally identical to each other, but use different syntax. You should use version 4, or version 3 if you have an aversion to dot-syntax.
Generally, dot notation is just syntactical sugar.
But in this case, there actually is some difference.
[cmController currentPageNo];
This will use the class's instance variable directly to get your cmController. It will then send the currentPageNo to it.
self.cmController.currentPageNo;
This, on the other hand, will use the current class's property definition to get the cmController via the class's ivar.
This means, basically, the the first is slightly more efficient than the second. Not because you used dot notation, but because you used cmController directly instead of self.cmController. [whatever currentPageNo] is the same as whatever.currentPageNo.
These lines are equivalent except for the syntax used:
[cmController currentPageNo];
cmController.currentPageNo;
On the other hand, these lines are equivalent except for the syntax used:
self.cmController.currentPageNo;
[[self cmController] currentPageNo];
I hope that's clear.
You can read about dot notation here.
There's no difference, functionally; objective C 2.0 just introduced the dot notation, giving those who aren't as into the brackets a way out.
EDIT:
As the comments pointed out, of course this is wrong. I was responding to the (unasked) question of "what's the difference between [cmController currentPageNo]; and self.cmController.currentPageNo;?"
Nick's answer gives the true answer, which is that the first line directly accesses the variable, while the second line uses the variable's getter method. The two lines also differ in that the first uses typical bracket notation, while the second does indeed use the new dot notation from objective C 2.0.

Purpose of Scala's Symbol? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What are some example use cases for symbol literals in Scala?
What's the purpose of Symbol and why does it deserve some special literal syntax e. g. 'FooSymbol?
Symbols are used where you have a closed set of identifiers that you want to be able to compare quickly. When you have two String instances they are not guaranteed to be interned[1], so to compare them you must often check their contents by comparing lengths and even checking character-by-character whether they are the same. With Symbol instances, comparisons are a simple eq check (i.e. == in Java), so they are constant time (i.e. O(1)) to look up.
This sort of structure tends to be used more in dynamic languages (notably Ruby and Lisp code tends to make a lot of use of symbols) since in statically-typed languages one usually wants to restrict the set of items by type.
Having said that, if you have a key/value store where there are a restricted set of keys, where it is going to be unwieldy to use a static typed object, a Map[Symbol, Data]-style structure might well be good for you.
A note about String interning on Java (and hence Scala): Java Strings are interned in some cases anyway; in particular string literals are automatically interned, and you can call the intern() method on a String instance to return an interned copy. Not all Strings are interned, though, which means that the runtime still has to do the full check unless they are the same instance; interning makes comparing two equal interned strings faster, but does not improve the runtime of comparing different strings. Symbols benefit from being guaranteed to be interned, so in this case a single reference equality check is both sufficient to prove equality or inequality.
[1] Interning is a process whereby when you create an object, you check whether an equal one already exists, and use that one if it does. It means that if you have two objects which are equal, they are precisely the same object (i.e. they are reference equal). The downsides to this are that it can be costly to look up which object you need to be using, and allowing objects to be garbage collected can require complex implementation.
Symbols are interned.
The purpose is that Symbol are more efficient than Strings and Symbols with the same name are refered to the same Symbol object instance.
Have a look at this read about Ruby symbols: http://glu.ttono.us/articles/2005/08/19/understanding-ruby-symbols
You can only get the name of a Symbol:
scala> val aSymbol = 'thisIsASymbol
aSymbol: Symbol = 'thisIsASymbol
scala> assert("thisIsASymbol" == aSymbol.name)
It's not very useful in Scala and thus not widely used. In general, you can use a symbol where you'd like to designate an identifier.
For example, the reflection invocation feature which was planned for 2.8.0 used the syntax obj o 'method(arg1, arg2) where 'o' was a method added to Any and Symbol was added the method apply(Any*) (both with 'pimp my library').
Another example could be if you want to create an easier way to create HTML documents, then instead of using "div" to designate an element you'd write 'div. Then one can imagine adding operators to Symbol to make syntactic sugar for creating elements