Showing posts with label NSThread. Show all posts
Showing posts with label NSThread. Show all posts

Friday, April 19, 2013

NSThread setStackSize example objc


setStackSize:

Sets the stack size of the receiver.
- (void)setStackSize:(NSUInteger)s
Parameters
s
The stack size for the receiver. This value must be in bytes and a multiple of 4KB.
Discussion
You must call this method before starting your thread. Setting the stack size after the thread has started changes the attribute size (which is reflected by the stackSize method), but it does not affect the actual number of pages set aside for the thread.
Example - setStackSize

{
thread=[[NSThread alloc]initWithTarget:self selector:@selector(fibnocciForLoop) object:nil];
[thread start]; 
[thread setStackSize:4096]; // multiple of 4KB
}

NSThread isMainThread example objc


isMainThread

Returns a Boolean value that indicates whether the receiver is the main thread.
- (BOOL)isMainThread
Return Value
YES if the receiver is the main thread, otherwise NO.

Example - isMainThread

__block NSInteger alertResult; // The __block modifier makes alertResult writable
                               // from a referencing block.
void (^ getResponse)() = ^{
    NSAlert *alert = …;
    alertResult = [NSAlert runModal];
};

if ([NSThread isMainThread]) {
    // We're currently executing on the main thread.
    // We can execute the block directly.
    getResponse();
} else {
    dispatch_sync(dispatch_get_main_queue(), getResponse);
}

// Check the user response.
if (alertResult == …) {
    …
}

NSThread initWithTarget example objc


initWithTarget:selector:object:

Returns an NSThread object initialized with the given arguments.
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
Parameters
target
The object to which the message specified by selector is sent.
selector
The selector for the message to send to target. This selector must take only one argument and must not have a return value.
argument
The single argument passed to the target. May be nil.
Return Value
An NSThread object initialized with the given arguments.
Discussion - [NSThread initWithTarget: selector: object:]
For non garbage-collected applications, the method selector is responsible for setting up an autorelease pool for the newly detached thread and freeing that pool before it exits. Garbage-collected applications do not need to create an autorelease pool.
The objects target and argument are retained during the execution of the detached thread. They are released when the thread finally exits.


Example


#import <Foundation/Foundation.h>
#define NOT_DONE 0
#define DONE 1

// this will need to be on some class that is calling the NSThread object
-(void) someFunc:(id) arg {
NSConditionLock* myLock = arg;
[myLock lock];
//do stuff that we need to know about in main
[myLock unlockWithCondition:DONE];
}


int main() {

NSConditionLock* finishedLock = [[NSConditionLock alloc]
initWithCondition: NOT_DONE];

NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(someFunc:) object:finishedLock];

[myThread start];

[finishedLock lockWhenCondition:DONE];

// now we can do whatever we need to do with the results from
// the thread we spawned

}

NSThread exit example objc

[NSThread exit example]

Create a NSThread object with following code fragment.

NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

To exit this thread externally, you can call NSThread:cancel method at some point and make your main thread method to check for whether it's cancelled or not by calling NSThread:isCancelled method.[NSThread exit example]

In your main thread method, you should check whether it's cancelled or not periodically.

// At some checkpoint

if([[NSThread currentThread] isCancelled])
{
   /* do some clean up here */
   [NSThread exit];
}

NSThread setThreadPriority example objc

[NSThread setThreadPriority example] Following code fragment shows how to set thread priority with NSThread setThreadPriority method. The priority, specified with a floating point number from 0.0 to 1.0, where 1.0 is highest priority.

[NSThread setThreadPriority example]

#import "MyObject.h"

@implementation MyObject

- (IBAction)myAction:(id)sender
{
[NSThread detachNewThreadSelector:@selector(threadTask) toTarget:self
withObject:nil];
[NSThread setThreadPriority:0.6];
NSLog([NSString stringWithFormat:@"%f",[NSThread threadPriority]]);

}
- (void)threadTask
{
    int i;
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

  for (i=1;i<100;i++) {
    NSLog([NSString stringWithFormat:@"%d",i]);
    }

    [pool release];
    [NSThread exit];
}
@end

NSThread threadDictionary example objc

Following code shows an example of  NSThread threadDictionary method. It uses NSThread threadDictionary to set some value for key to indicated whether to exit the thread or not.

Example - threadDictionary
- (void) myThreadMain{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    BOOL exitNow = NO;
    NSRunLoop* runLoop = [NSRunLoop currentRunLoop];

    // Add the exitNow BOOL to the thread dictionary.                               
    NSMutableDictionary* threadDict = [[NSThread currentThread] threadDictionary];
    [threadDict setValue:[NSNumber numberWithBool:exitNow] forKey:@"ThreadShouldExitNow"];

    // Install an input source.                                                                                                                                                                                                                                               
//  [self myInstallCustomInputSource];                                                                                                                                                                                                                                        

    while (!exitNow)
    {
        // Do one chunk of a larger body of work here.                                                                                                                                                                                                            

        // Run the run loop but timeout immediately if the input source isn't waiting to fire.                                                                                                                                                                                
        [runLoop runUntilDate:[NSDate date]];

        // Check to see if an input source handler changed the exitNow value.                                                                                                                                                                                                 
        exitNow = [[threadDict valueForKey:@"ThreadShouldExitNow"] boolValue];
    }

    [pool release];
}

Wednesday, April 17, 2013

NSThread example ios

[NSThread example] Following code fragment shows an NSThread example. It explains how to create a NSThread object and how to write target Thread Method. How to process screen display in thread run-loop. This NSThread example also demonstrates how to sleep the thead with NSThread:sleepForTimeInterval method.

// Creation Method 1.
//
[NSThread detachNewThreadSelector:@selector(_th) toTarget:self withObject:nil];

// Creation Method 2.
//
NSThread *thTime;
thTime = [[NSThread alloc] initWithTarget:self selector:@selector(_th) object:nil];
[thTime start];

// Implementation of main Thread Run-Loop.
//
- (void)_th {

 // Create auto release pool for the thread.
//

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

 // Check whether current thread is externally terminated or not.
while([[NSThread currentThread] isCancelled] == NO)    
{
NSLog(@"th 222");
NSString *t = [NSString stringWithFormat:@"%i", [lbText.text intValue] + 1];

  // Call main thread for displaying on the screen.
//
[self performSelectorOnMainThread:@selector(mainThreadSetText:) withObject:t waitUntilDone:YES];  

[NSThread sleepForTimeInterval:1.0];      // Sleep for a time.
}
[pool release];
}

//  Screen processing should be done outside the Thread.
- (void) mainThreadSetText:(NSString*)text
{
lbText.text = text;
}

- (void) _stop
{
[thTime cancel];
}

Monday, May 9, 2011

NSThread Example 3

NSThread creation example by NSThread alloc and init.

NSThread *myThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadFunc:) object:nil];
[myThread start];


Simple enough!

NSThread isCancelled example objc

[An NSThread isCancelled method example]

Create a NSThread object with following code fragment.


NSThread *newThread = [[NSThread alloc] initWithTarget:self selector:@selector(MyThread:) object:timer];

To stop this thread externally, you can call NSThread:cancel method at some
point and make your main thread method to check for whether it's cancelled or not
by calling NSThread isCancelled method.

In your main thread method, you should check whether it's cancelled or not periodically.


// At some checkpoint
if([[NSThread currentThread] isCancelled]) {
    /* do some clean up here */
    [NSThread exit];
}

NSThread example objc

A NSThread example that is very  simple.
Let's create and run a NSThread object on iPhoneOS.
First you should write a method that runs as a thread [NSThread Example]

1-(void) myTestThread:(id)anObject {
2
3     NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
4     //Your code here..
5     
6    [autoreleasepool release];
7    [NSThread exit];
8
9}


Then create a new NSThread object with detachNewThreadSelector method as following
code fragment. That's all pretty simple! [NSThread Example]

[NSThread detachNewThreadSelector:@selector(myTestThread:) toTarget:self withObject:nil];

NSThread Example objc

An NSThread example collected from http://iphoneappsmaker.tistory.com/516
When startThreadButtonPressed method is invoked, a new NSThread object is
created and detached with startTheBackgroundJob callback. This method
simples updates the progressbar. [NSThread Example]




- (IBAction) startThreadButtonPressed:(UIButton *)sender {

threadStartButton.hidden = YES;
threadValueLabel.text = @"0";
threadProgressView.progress = 0.0;
[NSThreaddetachNewThreadSelector:@selector(startTheBackgroundJob) toTarget:selfwithObject:nil];

}

- (void)startTheBackgroundJob {

NSAutoreleasePool *pool = [[NSAutoreleasePoolalloc] init];
// wait for 3 seconds before starting the thread, you don't have to do that. This is just an example how to stop the NSThread for some time
[NSThreadsleepForTimeInterval:3];
    [selfperformSelectorOnMainThread:@selector(makeMyProgressBarMoving) withObject:nilwaitUntilDone:NO];
    [pool release];

}

- (void) makeMyProgressBarMoving{

    
float actual = [threadProgressViewprogress];
threadValueLabel.text = [NSStringstringWithFormat:@"%.2f", actual];
if (actual < 1) {
threadProgressView.progress = actual + 0.01;
[NSTimerscheduledTimerWithTimeInterval:0.5target:selfselector:@selector(makeMyProgressBarMoving) userInfo:nilrepeats:NO];
}
elsethreadStartButton.hidden = NO;

}

Friday, May 6, 2011

Background method execution using NSThread code example objc

You can execute a method in background mode using detachNewThreadSelector method. For proper memory management, the target method maintains its own AutoreleasePool. [detachNewThreadSelector]


[NSThread detachNewThreadSelector:@selector(doSomethingInBack:) toTarget:self withObject:nil];

-(void) doSomethingInBack:(id)anObject {
NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
// 다른 스레드로 실행할 코드 작성.p
[NSThread exit];
// 메모리 릭 방지.
[autoreleasepool release];
}