Objective-C, global variables and threads - objective-c

I've made several Objective-C class files. Two of them had the same name for a global variable. When the program was running a thread from one file but was also accessing code from the other file on another thread, the thread seemed to get confused on what global variable belongs to it.
Is this a true issue or was my code wrong? I seem to have fixed it by changing the variable name.

I would go with your code was wrong, but I think there's a more fundamental thing you are misunderstanding here.
A thread doesn't per-se belong to a file, or own anything. What really happened is say you have two functions, one in each of your file, the compiler (since your variables aliased each other) chose to use one variable in one file, and another in another. This has nothing to do with threads, or anything else.
Furthermore, if you are looking for a thread local variable, you might want to look at the threadDictionary property of NSThread http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSThread_Class/Reference/Reference.html

Related

Do Objective-C objects get their own copies of instance methods?

I'm new to Objective-C and was wondering if anyone could provide any information to clarify this for me. My (possibly wrong) understanding of object instantiation in other languages is that the object will get it's own copies of instance variables as well as instance methods, but I'm noticing that all the literature I've read thus far about Objective-C seems to indicate that the object only gets copies of instance variables, and that even when calling an instance method, program control reverts back to the original method defined inside the class itself. For example, this page from Apple's developer site shows program flow diagrams that suggest this:
https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW1
Also in Kochan's "Programming in Objective-C", 6th ed., pg. 41, referring to an example fraction class and object, the author states that:
"The first message sends the setNumerator: message to myFraction...control is then sent to the setNumerator: method you defined for your Fraction class...Objective-C...knows that it's the method from this class to use because it knows that myFraction is an object from the Fraction class"
On pg. 42, he continues:
"When you allocate a new object...enough space is reserved in memory to store the object's data, which includes space for its instance variables, plus a little more..."
All of this would seem to indicate to me that there is only ever one copy of any method, the original method defined within the class, and when calling an instance method, Objective-C simply passes control to that original copy and temporarily "wires it" to the called object's instance variables. I know I may not be using the right terminology, but is this correct? It seems logical as creating multiple copies of the same methods would be a waste of memory, but this is causing me to rethink my entire understanding of object instantiation. Any input would be greatly appreciated! Thank you.
Your reasoning is correct. The instance methods are shared by all instances of a class. The reason is, as you suspect, that doing it the other way would be a massive waste of memory.
The temporary wiring you speak of is that each method has an additional hidden parameter passed to it: a pointer to the calling object. Since that gives the method access to the calling object, then it can easily access all of the necessary instance variables and all is well. Note that any static variable exists in only a single instance as well and if you are not aware of that, unexpected things can happen. However, regular local variables are not shared and are recreated for each call of a method.
Apple's documention on the topic is very good so have a look for more info.
Just think of a method as a set of instructions. There is no reason to have a copy of the same method for each object. I think you may be mistaken about other languages as well. Methods are associated with the class, not individual objects.
Yes, your thinking is more or less right (although it's simpler than that: behind the scenes in most such languages methods don't need to be "wired" to anything, they just take an extra parameter for self and insert struct lookups before references to instance variables).
What might be confusing you is that not all languages work this way, in their implementations and semantically. Object-oriented languages are (very roughly) divided into two camps: class-based, like Objective-C; and prototype-based, like Javascript. In the second camp of languages, a method or procedure really is an object in its own right and can often be assigned directly to an object's instance variables as well - there are no classes to lookup methods from, only objects and other objects, all with the same first-class status (this is an oversimplification, good languages still allow for sharing and efficiency).

Thread safe hooking of DirectX Device

I successfully hooked BeginScene/EndScene methods of DirectX9's DeviceEx, in order to override regions on the screen of a graphics application. I did it by overriding the first 'line' of the function pointed by the appropriate vtable entry (42 for EndScene) with an x86 jump command.
The problem is that when I would like to call the original EndScene method, I have to write the original code overriden by the jump. This operation is not thread safe, and the application has two devices used by two threads.
I tried overriding the vtable entry or copying it and override the COM interface pointer to the vtable, neither ways worked. I guess the original function pointer is cached somewhere or was optimized in the compilation.
I thought about copying the whole original method body to another memory block, but two problems I'm afraid of: (1) (the easy one I think) I don't know how to discover the length of the method and (2) I don't know if the function body stores offsets which are relative to the location where the function is in memory.
I'm trying to hook WPF's device, if it can help somehow.
Do anyone know a thread safe way for such hooking?
Answering my own question: It seems that for my purpose (performing another method before or instead of the original one within my own process), 'trampoline' is the answer. Generally it means I need to make another code segment that makes exactly what the overriden assembly commands did.
Because it is not an easy task, using an external library is recommended.
A discussion about this topic:
How to create a trampoline function for hook

I'm having trouble applying a solution found in SO in my iOS app. Can someone show me the big picture?

in the Stack Overflow posting:
How do I create a global UIManagedDocument instance per document-on-disk shared by my whole application using blocks?
Alan asked how to create a global UIManagedDocument to be used throughout his entire app. He provided code slices of his attempt. Kevinpo provided an answer which made perfect sense to Alan.
But I started out with the same problem, and can't make heads or tails out of their collective postings.
Specifically:
Alan's code references an object called managedDocumentDictionary,
but does not explain how to create it so I get an 'undeclared
identifier' compilation error.
Alan starts out stating that he wants to create a helper method to
retrieve a UIManagedDocument, yet throughout both his and Kevin's
code, neither actually show defining a helper method with .h and .m
files.
So, if possible, can anyone make sense of what they are saying and help me understand how it all fits together? Perhaps:
A helper Class definition,
How does one get the ball rolling, i.e., where do I initially create this UIManagedDocument,
Once created, How do I get the document in other TableViewControllers?
A sample of where this should be invoked - in the AppDelegate? or each TableViewController?
Maybe even a sample project?
Thanks to all for any interpretations you can offer.
That post shows how to access a document, based on a name. The dictionary is a mapping from names to UIManagedDocument instances. Thus, he can ask for document #"Foo" and the code will go look up #"Foo" in the dictionary. If it is there, the UIManagedDocument will be returned. If it is not there, then a new one will be created and placed in the dictionary (and the passed-in completion block will be called).
His question was basically, how to pass a completion block to the function, and have that function call the completion block he passed in.

When do I need to copy a block?

I don't really know when do I need to copy a block.
The documentation says when you expect the block to be used after destruction of the scope within which it was declared.
Do I need to copy it when I'm using them as callback methods for example? By copy I mean creating a copy property for my block and saving the block there or somehow sending a copy message. The scope is probably destroyed when a download or something similar is finished. So do I need to copy the block in that case? Can I create circular references this way?
Right now I have a downloader class (to test blocks only, it's too dangerous for me to use it yet) that uses a completion block and when I copy the block the view controller that created the block and the downloader class is not released.
Can you give me some good examples especially using them for finishing async operations like file downloads?
Thanks.
Most of the time methods that take callbacks will copy the block for you
I can think of two cases when you need to copy a block yourself in Objective-C
when you're returning a block from a function
when you're saving a block to a class variable (this is the case that happens when you're implementing a method that accepts a callback at a later point).
Since these are the times the block will drop out of scope before they're used or dealt with.

OOP question about functions that struck me all of a sudden

May be my question is stupid. But i would like to get it cleared. We know that functions are loaded in memory only once and when you create new objects, only instance variables gets created, functions are never created. My question is, say suppose there is server and all clients access a method named createCustomer(). Say suppose all clients do something which fired createCustomer on server. So, if the method is in middle of execution and new client fires it. Will the new request be put on wait? or new request also will start executing the method? How does it all get managed when there is only one copy of function in memory? No book mentions answers to this type of questions. So i am posting here where i am bound to get answers :).
Functions are code which is then executed in a memory context. The code can be run many times in parallel (literally in parallel on a multi-processor machine), but each of those calls will execute in a different memory context (from the point of view of local variables and such). At a low level this works because the functions will reference local variables as offsets into memory on something called a "stack" which is pointed to by a processor register called the "stack pointer" (or in some interpreted languages, an analog of that register at a higher level), and the value of this register will be different for different calls to the function. So the x local variable in one call to function foo is in a different location in memory than the x local variable in another call to foo, regardless of whether those calls happen simultaneously.
Instance variables are different, they're referenced via a reference (pointer) to the memory allocated to the instance of an object. Two running copies of the same function might access the same instance variable at exactly the same time; similarly, two different functions might do so. This is why we get into "threading" or concurrency issues, synchronization, locks, race conditions, etc. But it's also one reason things can be highly efficient.
It's called "multi-threading". If each request has its own thread, and the object contains mutable data, each client will have the opportunity to modify the state of the object as they see fit. If the person who wrote the object isn't mindful of thread safety you could end up with an object that's in an inconsistent state between requests.
This is a basic threading issue, you can look it up at http://en.wikipedia.org/wiki/Thread_(computer_science).
Instead of thinking in terms of code that is executed, try to think of memory context of a thread that is changed. It does not matter where and what the actual code happens to be, and if it is the same code or a duplicate or something else.
Basically, it can happen that the function is called while it was already called earlier. The two calls are independent and may even happen to run in parallel (on a multicore machine). The way to achieve this independence is by using different stacks and virtual address spaces for each thread.
There are ways to synchronize calls, so additional callers have to wait until the first call finishes. This is also explained in the above link.