// 스레드는 한 함수를 관리한다.
// 때문에 새로운 스레드가 실행되면서 함수를 실행하고, 함수가 끝나면 자연히 스레드가 종료된다.
// 그래서 함수 내부에서 무한 루프를 돌면 스레드가 죽지않고 계속 유지됩니다.
// 메인스레드의 이벤트루프가 이런 원리임. 이벤트루프에서 나와서 스레드가 끝난다는 것은 앱의 종료를 의미
// 생성 1
[NSThread detachNewThreadSelector:@selector(_th) toTarget:self withObject:nil];
// 생성 2
NSThread *thTime;
thTime = [[NSThread alloc] initWithTarget:self selector:@selector(_th) object:nil];
[thTime start];
- (void)_th {
// 스레드안에서의 처리들은 지역 오토릴리즈를 해야 한다.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
while([[NSThread currentThread] isCancelled] == NO) // 현재 스레드를 반환하고 상태를 체크
{
NSLog(@"th 222");
NSString *t = [NSString stringWithFormat:@"%i", [lbText.text intValue] + 1];
// 표현에 관계된 것들은 메인스레드로 보내자.
[self performSelectorOnMainThread:@selector(mainThreadSetText:) withObject:t waitUntilDone:YES];
[NSThread sleepForTimeInterval:1.0]; // 스레드에 대한 sleep 기능의 함수
}
[pool release];
}
// 화면처리의 경우는 반드시 스레드 밖에서 처리를 해줘야한다.
- (void) mainThreadSetText:(NSString*)text
{
lbText.text = text;
}
- (void) _stop
{
[thTime cancel];
// cancel, 한번 스레드가 끝난 객체 즉 isFinished가 YES된 객체는 다시 실핼할 수 없다. 다시하고 싶은경우는 해제후 새로 만들어야함.
}
/* //////////////////////////////////////////////////// NSThread.h
Copyright (c) 1994-2010, Apple Inc. All rights reserved.
*/////////////////////////////////////////////////////
#import <Foundation/NSObject.h>
#import <Foundation/NSDate.h>
@class NSArray, NSMutableDictionary, NSDate;
@interface NSThread : NSObject {
@private
id _private;
uint8_t _bytes[44];
}
+ (NSThread *)currentThread;
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument;
+ (BOOL)isMultiThreaded;
- (NSMutableDictionary *)threadDictionary;
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
+ (void)exit;
+ (double)threadPriority NS_AVAILABLE(10_2, 2_0);
+ (BOOL)setThreadPriority:(double)p NS_AVAILABLE(10_2, 2_0);
#if MAC_OS_X_VERSION_10_5 <= MAC_OS_X_VERSION_MAX_ALLOWED || __IPHONE_2_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
- (double)threadPriority NS_AVAILABLE(10_6, 4_0);
- (void)setThreadPriority:(double)p NS_AVAILABLE(10_6, 4_0);
+ (NSArray *)callStackReturnAddresses;
+ (NSArray *)callStackSymbols NS_AVAILABLE(10_6, 4_0);
- (void)setName:(NSString *)n;
- (NSString *)name;
- (NSUInteger)stackSize;
- (void)setStackSize:(NSUInteger)s;
- (BOOL)isMainThread;
+ (BOOL)isMainThread; // reports whether current thread is main
+ (NSThread *)mainThread;
- (id)init; // designated initializer
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument;
- (BOOL)isExecuting;
- (BOOL)isFinished;
- (BOOL)isCancelled;
- (void)cancel;
- (void)start;
- (void)main; // thread body method
#endif
@end
FOUNDATION_EXPORT NSString * const NSWillBecomeMultiThreadedNotification;
FOUNDATION_EXPORT NSString * const NSDidBecomeSingleThreadedNotification;
FOUNDATION_EXPORT NSString * const NSThreadWillExitNotification;
@interface NSObject (NSThreadPerformAdditions)
#if MAC_OS_X_VERSION_10_2 <= MAC_OS_X_VERSION_MAX_ALLOWED || __IPHONE_2_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray*)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
#endif
#if MAC_OS_X_VERSION_10_5 <= MAC_OS_X_VERSION_MAX_ALLOWED || __IPHONE_2_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;
#endif
@end
출처 : http://blog.naver.com/hana_815/60120426652