Pros & Cons of different ways to create a timer in Objective-C - objective-c

From the documentation:
There are three ways to create a timer:
Use the scheduledTimerWithTimeInterval:invocation:repeats: or
scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: class
method to create the timer and schedule it on the current run loop in
the default mode.
Use the timerWithTimeInterval:invocation:repeats: or
timerWithTimeInterval:target:selector:userInfo:repeats: class method
to create the timer object without scheduling it on a run loop. (After
creating it, you must add the timer to a run loop manually by calling
the addTimer:forMode: method of the corresponding NSRunLoop object.)
Allocate the timer and initialize it using the
initWithFireDate:interval:target:selector:userInfo:repeats: method.
(After creating it, you must add the timer to a run loop manually by
calling the addTimer:forMode: method of the corresponding NSRunLoop
object.)
What are the pros and cons of the above methods, in terms of:
performance (memory consumption, etc)
ease of use (possibility to control/ start/ stop the timer in any point of program)
thread-safe
Look forward to your reply.

Related

Wait for a thread inside a C++ static object

I have a static object that needs to initialize an imaging API. The allocated resources of this imaging API need to be released by the same thread.
So I'm starting a thread in my static object that initializes everything and then waits for a counter to reach zero. When this happens the thread cleans all up and finishes.
This is an unmanaged class inside a managed library, so I can't use System::Threading::Thread (needs a managed static member function) or std::thread (compiler error, not supported with /clr).
So I have to start my thread like:
CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&Initialize, this, 0, 0);
All works fine, the init is done and the API functions work. But when I close the application I see that the usage counter of my static object reaches zero but the clean up function is never called by the thread, as if the thread was killed. Is there a way to make sure the thread will continue to exist and execute until its end?
After turning this around in all possible ways and adding events etc I guess this is not possible so I'll have to change the structure of my code and encapsulate the non managed class inside a managed class, and add the thread to the managed class.
I think you could proceed in one of two ways:
Wrap the resources in RAII-style classes, and refactor to have the objects' lifetimes be on the stack of your created thread, ensuring their destructors get called when the thread loop exits without having to call any additional cleanup. If there is no issue with the thread returning correctly when your counter reaches 0, this should be the simplest and cleanest way of addressing this.
I'm thinking you could intercept the WM_CLOSE message using window procedures, process necessary cleanup and then pass the message on, effectively "stalling" it until you are ready to close. Note that even though you are in a DLL you can still set up a window procedure and message pump system, you don't need a GUI to do that. I am however not 100% sure on whether you'll receive the WM_CLOSE message that concerns the application that "owns" your DLL, it's not something I've tried out yet.
You will have to implement some form of messaging through events within your thread's loop however, as the WindowProc will be called on a different thread, so you know when to call the cleanup procedure.
I also am not very familiar with CLR, so there might be a simpler way of interacting with those APIs than with raw C++ calls and handles.

Objective-C: use NSThread with a function or block, without need for an additional object

I have an Objective-C app where I need to run a function in a separate thread. This function will run continuously with a run loop and will need to be canceled at a later date, so I think the right thing to use is NSThread. I don't think this is an appropriate time to use Grand Central Dispatch. (Do correct me if I'm wrong.)
NSThread requires me to allocate and maintain a separate object with a method that will be executed in the new thread, e.g. [[NSThread alloc] initWithTarget:someObject selector:#selector(runThread) object:nil]
Granted this may seem like a trifling complaint, but is there any way for me to start a thread like this without needing this separate object? I'd like to just use a C-style function or a block.
The documentation is organized a bit oddly, but NSThread has -initWithBlock: and +detachNewThreadWithBlock:.

VB.Net: appropriate synchronisation object for waiting, not protecting

I have BBController instances (my custom objects), where some may need to wait for a few others to complete first (dependencies). I have decided to have each controller lock some synchronisation object at initialisation, lets call it a Padlock, and then unlock it when its done processing. When its unlocked, any controllers that depend (or were waiting for) on the aforementioned controller can then continue. So this is not about protecting a section of code by allowing one thread, but instead telling anything that that depends on an output to wait until that output is available.
I have experience with Semaphores in objective c, so I thought I could use those here by having each controller initialise its semaphore with a value of 0, and then when finished signal it with a value of infinite or max. While that would work, I'm sure there is a better locking object to make use of, since the value property of Semaphore is of no use here since as many BBControllers can continue when the semaphore is signalled. I am new to VB.Net

sequential methods execution obj-c

Very beginner obj-c question.
My task is to do simple sequence when view loads:
pause 2 secons
method1 execution
pause 2 seconds
method2 execution
pause 2 seconds
method3 execution
I write this code for iOS5+ so blocks or other features can be used. I tried
[NSThread sleepForTimeInterval:x];
to make the pauses between methods executions, but three pauses added to one and I have one big pause, so it's wrong piece.
How to do this in right way?
Sleeping an NSThread is never the right way to handle timed method execution. You want NSTimer, which you can set to either fire the same method after two seconds (then have that method determine which selector to perform next), or have three timers set to fire two seconds after each other, each calling a different method.
You could use performSelector:withObject:afterDelay:, or as CodaFi said, an NSTimer. Either method allows to to pass an object to the method, and that object could be an array or dictionary, if you need to pass multiple arguments.
I'd chain the methods:
call 1. method and make it call 2.
method should call 3.
should proceed to 4.
...

Is Cocoa's Application Delegate Scope Limited?

Let's say I want to create new objects than exist throughout the duration of the program. I need them to be created at startup and continuously run background tasks throughout the program. If I put them in the application's delegate under applicationDidFinishLaunching, do the objects exist throughout the duration of the program or just the scope of applicationDidFinishLaunching? After applicationDidFinishLaunching returns, do my objects go out of scope or do they keep running background tasks? If so, how do I ensure the objects exist throughout the duration of the program and continue to run background tasks?
The "background tasks" are being run on separate threads. I am using Objective-C with Xcode 3.2.6 on Mac OS X Snowleopard.
The lifetime of Objective-C objects is controlled manually (assuming you're not using garbage collection or ARC). You shouldn't ask if they exist throughout the duration of the program—instead, you should make sure that each reference to an object, no matter where it is (main thread, background thread) is properly retained. See the basic memory management rules.
Specifically, if you create an object with [[MyClass alloc] init], you now have an owning reference to that object (that you are responsible for eventually releasing). If you then start a new thread and give that thread a reference to your object, that thread should call [obj retain] to ensure that the object will continue to exist, and [obj release] when it's done with the object.