Will ARC tell me when I must use __block? - objective-c

AFAIK, __block is used when you're changing, inside the block, the address that a variable (declared outside the block) points to.
But, what if I'm changing the value that the variable points to but the pointer stays the same? E.g., what if I have NSMutableArray *array and am just doing [array addObject:object] inside the block? In this case, I'm not changing the pointer array, but I'm changing the value it points to. So, must I still use __block in declaring NSMutableArray *array?

You only need __block if you are changing the value of the variable.
I.e. if you have:
NSArray* foo;
You only need __block if you change the value of foo. Now, keep in mind that foo is nothing more than "a pointer to a thing that is typed NSArray". I.e. foo is effectively a 64 bit or 32 bit integer, depending on platform. If you change that integer, you need __block. If you don't, you don't need __block.
So, no, you don't need __block to call addObject: on the array since you aren't actually changing the value of foo.
If you were to do something like foo = (expression);, then you'd need __block.
(note that this is one of the reasons why concurrent programming under OO is so damned hard... it is exceptionally hard to define the "domain of variance" for any given execution path)

Related

Is it necessary to use __block type specifier for mutable objects altered in blocks?

Say map is a NSDictioanry, my understanding is since the address of res does not change in the block we don't need to use __block for it. Is this correct?
//__block NSMutableArray *res = [#[] mutableCopy];
NSMutableArray *res = [#[] mutableCopy];
__block NSInteger i = 0;
[map enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSArray *v, BOOL *stop) {
[res addObject:v];
i++;
}];
By the way I have run the code it works fine.
The __block type specifier is only necessary for the storage of mutable items which would normally go on the stack.
Since a block is not guaranteed to be called only within the scope of the method that creates it (this is called escaping), it might need to mutate variables which it references after they've gone away. References to things that go on the stack (like i in your example) can become dangling pointers if the block is held onto past the end of the original method or function, so if they are to be mutated, they need to be stored somewhere other than the stack. The __block specifier tells the compiler to put the variable in separate storage which will be valid whenever the block is called.
For things which are heap allocated (like res above), this is not necessary — since the pointer to the object will not change as long as the object is around (which it should be, since the block will retain it by default), the local storage of the object pointer does not need to be put in alternative storage, and can stay on the stack.
If you'd like to read more on this, the Blocks and Variables documentation page has in-depth info on memory management with blocks, and more on the __block storage type.
That is correct. __block is only necessary if you assign (= or equivalent) to the variable inside the block, or if you want to block to be able to see assignments to the variable outside the block after the block was created. (This is true regardless of what the variable's type is.)
Here, The variable i is assigned to inside the block, with the ++ operator, hence __block is necessary. The variable res is never assigned to anywhere; the variable res is read from (not assigned to) inside the block.

Assigning object pointers

Is this pointer assignment correct?
customclass.somearray = &*otherarray;
where somearray and otherarray are NSArray objects.
If not, how do I solve my problem:
I want to share this otherarray object with customclass.somearray. And I want all changes
made to customclass.somearray to be made to the original otherarray too.
Doing it this way, it works. I just want to ask, is it correct?
Your two variables are pointers of the same type, so just assign one to the other:
customclass.somearray = otherarray;
The way you have written this is unnecessary. Using the dereference operator * essentially gives you the "contents" of the pointer. The address-of operator & correspondingly gives you the address of whatever you apply it to. Your pointer otherarray contains an address. If you dereference that address and then take the address of that, you end up right back where you started.
Be aware that the left side of this assignment is a property access (assuming that customclass is also an object and not just a struct). This means that the compiler will change your expression into:
[customclass setSomearray:&*otherarray];
// And my version will be changed into:
[customclass setSomearray:otherarray];
That is, it becomes a method call rather than a simple assignment. This does not affect the syntax you should use, however.
When working in Objective-C, you never deal with objects directly, but always refer to them via pointers. Always. In C++, you can declare an actual object on the stack, for example, but you never do that in Objective-C. So, if you have:
NSArray *otherArray = [NSArray arrayWithObjects:#"foo", #"bar", nil];
then otherArray is a pointer to an instance of NSArray. Likewise, your somearray property will be of type NSArray*, so the types will match and you can just assign one to the other:
customclass.somearray = otherarray;
Hope that helps.

Use of an intermediary to initialize an object

I've always seen that we use an intermediary object, for example, creating an array to fill in another array:
characters = [[NSArray alloc] initWithObjects:#"Antony", #"Artemidorus", #"Brutus", nil];
play.characters = characters;
[characters release];
with characters being an NSArray in the object play.
I saw the same thing with a #property and its self: we did not add the new items directly into this property, just as we don't directly fill in characters in the example above. Is this only about "style"?
This is not a matter of style.
play.characters is a property, and that can "contain" an existing array or nil, but even if it "contains" an existing array, you can't change the contents of an NSArray, so you'll have to create a new one and assign that to the property.
Assigning to a property will, if all was declared well, cause its setter method to run (which could be created by the compiler, if you used #synthesize, or written by you, in code) and that will take care of removing any existing array, assigning the new one and retaining it.
There is actually only one array in play in that little piece of code.
It is not the array that is intermediate, but the variable holding a pointer to it - in this case the variable characters.
This is what happens:
The expression
[[NSArray alloc] initWithObjects:#"Antony", #"Artemidorus", #"Brutus", nil]
allocates an object and initialises it with three NSStrings (which are themselves objects, but let's leave that out for a moment). The initialisation also includes an increment of the retain count, so it is one from the get-go.
This newly created object lives at a given position in memory, say 0100H. This position is then stored in the variable characters. In C terms we say that characters is a pointer to the object.
Then the property #"characters" of the object play is set to point to the same position in memory as the local variable characters. There are therefore now two variables (of which one is also a property) that point to the same object, or, if you prefer, to the same position in memory. If the property is of type retain, this will automatically increment the retain count of the object, so it is now 2.
With the release message in the last line, the object decrements its retain count by one, so at the end of this code snippet, the object is pointed to by the play.characters property, and it has a retain count of one.
To be really clean, this code should probably set the local variable to nil, to avoid confusion between variables holding pointers to the object and the retain count.
All this was meant to show that there really is only one array in play here, but two variables that point to it. So there are not as many computer resources being wasted as it might seem at a first glance.
If you wanted to do it all in a single line, you could write something like this:
play.characters = [[[NSArray alloc] initWithObjects:#"Antony", #"Artemidorus", #"Brutus", nil] autorelease];
but the exact working of this is less clear as it involves one of those mysterious autoreleases, i.e., a release that is handled automatically and postponed to some later stage.
This is a long description, but I hope it sheds some light on what is going on.

How do you declare instance of the class in Objective C?

Let's imagine I have Fraction class. So, the correct way to create instance of it is:
Fraction *myFraction;
or
myFraction = Fraction;
or
myFraction = [Fraction new];
or something else?
In the book i'm studying the correct one is first, but it looks unreasonable to me. Why do we have to create a pointer for it? Why don't we make the real instance?
That first expression means - give me a pointer to the new instance of Fraction class, doesn't it?
The first declares a variable named myFraction of type Fraction *, but doesn't create anything, nor initialize myFraction. The second isn't valid. The third creates a new Fraction and assigns it to a previously declared variable named myFraction. Often in Objective-C, you'll declare and initialize a variable in a single statement:
Fraction *myFraction = [[Fraction alloc] init];
As for whether to use new or alloc followed by init, it's largely a matter of taste.
Variables for storing objects are pointers in part because Objective-C inherited C's call-by-value semantics. When one variable is assigned to another (such as when passing it to a function), the value will be copied. At best, this is inefficient for immutable objects. At worst, it leads to incorrect behavior. Pointers are a way around call-by-value and the copy-on-assign semantics: the value of a variable with pointer type is just the pointer. It can be copied without touching the target object. The cost for this is you need some form of memory management.
It would be a good idea to read Kernihan and Ritchie's "The C Programming Language" so you can get an idea about how variables are declared.
There are two modes of allocation in C and Obj-C and C++: manual and automatic.
Integers and floats and characters and such are generally automatically declared. They are created when the declaration passes (i.e. int i), and deleted when the scope they were created in goes away, i.e. when you exit the block in which they were declared. They're called automatics. (it's also possible to declare them "static" but for the purposes of this discussion regarding allocation, these are the same)
Objects are too complicated to pass around to functions, as function parameters are "pass by value", meaning that the parameter gets a copy of the value being passed in, instead of the variable itself. It'd take a huge amount of time to copy a whole object all the time.
For this reason, you want to just tell the various functions where they can find the object. Instead of handing off a copy of the object, you hand off a copy of the address of the object. The address is stored in an automatic with a type of pointer. (This is really just an integer, but it's size is dictated by the hardware and OS, so it needs to be a special type.)
The declaration Fraction *myFraction; means "myFraction is a pointer, and just so you know, it's going to point to a Fraction later."
This will automatically allocate the pointer, but not the whole Fraction. For that to happen, you must call alloc and init.
The big reason why you have this two step process is that since we typically want objects to stick around for a while, we don't want the system automatically killing them at the end of a function. We need them to persist. We create places to hang the object in our functions, but those hangers go away when they aren't needed. We don't want them taking the object with them.
Ultimately, you might make declarations like this:
Fraction *myFraction = [[Fraction alloc] initWithNumerator: 2 Denominator: 3];
which says: "Make me a Fraction, and set it to be 2/3, and then put the address of that Fraction into 'myFraction'."
Why do we have to create a pointer for it? Why don't we make the real instance?
In Objective-C, every object is pointer type. So, you need to use either new or alloc/init.
Fraction *myFraction = [ Fraction new ] ;
or
Fraction *myFraction = [ [Fraction alloc] init ] ;
And myFraction needs to be released.
That first expression means - give me a pointer to the new instance of Fraction class, doesn't it?
No, you are just declaring a pointer of type Fraction. And the second statement is not even valid.

What does the Asterisk * mean in Objective-C?

Is it true, that the Asterisk always means "Hey, that is a pointer!"
And an Pointer always holds an memory adress?
(Yes I know for the exception that a * is used for math operation)
For Example:
NSString* myString;
or
SomeClass* thatClass;
or
(*somePointerToAStruct).myStructComponent = 5;
I feel that there is more I need to know about the Asterirsk (*) than that I use it when defining an Variable that is a pointer to a class.
Because sometimes I already say in the declaration of an parameter that the Parameter variable is a pointer, and still I have to use the Asterisk in front of the Variable in order to access the value. That recently happened after I wanted to pass a pointer of an struct to a method in a way like [myObj myMethod:&myStruct], I could not access a component value from that structure even though my method declaration already said that there is a parameter (DemoStruct*)myVar which indeed should be already known as a pointer to that demostruct, still I had always to say: "Man, compiler. Listen! It IIISSS a pointer:" and write: (*myVar).myStructComponentX = 5;
I really really really do not understand why I have to say that twice. And only in this case.
When I use the Asterisk in context of an NSString* myString then I can just access myString however I like, without telling the compiler each time that it's a pointer. i.e. like using *myString = #"yep".
It just makes no sense to me.
an * is actually an operator to de-reference a pointer. The only time it means "hey i'm a pointer" is during variable declaration.
Foo* foo // declare foo, a pointer to a Foo object
&foo // the memory address of foo
*foo // de-reference the pointer - gives the Foo object (value)
mmattax well covered the distinction between declaration (as a pointer) and dereferencing.
However, as to your point about:
(*myVar).myStructComponentX = 5;
to access a member of an instance of a C struct (as this is) you can do what you did , or more commonly you use the -> notation:
myVar->myStructComponentX = 5;
Objective-C is a little confusing here because it recently (in ObjC 2.0) introduced property syntax, which is a short cut for:
int val = [myObject someIntProperty];
and can now be written as:
int val = myObject.someIntProperty;
This is Objective C (2.0) syntax for accessing a property which you have declared (not an actual member variable), whereas your example was accessing a member of a C struct.
Make sure you are clear on the difference.
As I said in my answer of your previous question, #"yep" is already a pointer, so there is no need of * before myString which is also a pointer. In this case, you assign pointers not values.