달력

10

« 2024/10 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
2010. 5. 28. 21:32

[16일차]에러처리 Objective-C2010. 5. 28. 21:32

1. 에러 처리

에러가 발생하면 메서드나 함수의 리턴 값 형태로 에러의 발생을 리턴합니다.

파일 처리에는 이러한 에러 처리를 위한 객체를 대입하도록 되어 있습니다.

이 경우 에러 처리에 관련된 오브젝트를 대입하면 에러가 발생해도 프로그램이 중단되지 않고 적절한 메시지를 출력하도록 프로그램을 만들 수 있습니다.


2. 타이머

일정한 주기를 가지고 또는 일정 시간을 delay 한 후 실행해야 하는 프로그램이나 메서드가 있다면 이 때는 타이머 오브젝트를 이용할 수 있습니다.

이 클래스는 NSTimer.h에 정의되어 있습니다.



3. 스레드(Thread)

NSThread 클래스가 스레드 기능을 제공하며 NSThread.h 파일에 정의와 구현되어 있습니다.

실제 main 함수도 스레드로 동작합니다.
모든 Objective-c프로그램 1개 이상의 스레드 소유.
기본적으로 main도 하나의 main 스레드로 생성해서 실행

현재 스레드가 수행 중인지 아닌지 확인하는 메서드는 아래와 같습니다.

 

+(BOOL)isMultiThreaded

멀티 스레드인지 아닌 지 확인해주는 메서드. 과거 한번이라도 수행이 되었는지 확인

+(NSThread *)currentThread

현재 스레드를 나타내는 인스턴스 리턴

+(NSThread *)mainThread

현재의 main 스레드를 나타내는 인스턴스 리턴
---------------------------------------------------------------
#import <Foundation/Foundation.h>
int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSThread * thread;
    thread = [NSThread currentThread];
    if(thread !=nil)
     NSLog(@"현재 스레드가 동작중입니다");
    else
     NSLog(@"현재 스레드가 동작중이지 않습니다.");
    
    if(thread == [NSThread mainThread])
     NSLog(@"이 스레드는 main스레드 입니다.");
    else
     NSLog(@"이 스레드는 main스레드가 아닙니다");
    
    if([NSThread isMultiThreaded] == YES)
     NSLog(@"현재 프로그램은 멀티 스레드 환경입니다.");
    else
     NSLog(@"현재 프로그램은 멀티 스레드 환경이 아닙니다.");        
    
    [pool drain];
    system("pause");
    return 0;
}

---------------------------------------------------------------

스레드 생성하기

-(id) initWithTarget:(id)스레드 수행 주체 selector:@selector(스레드로 수행할 메서드:) object:인수로 넘겨줄 오브젝트-스레드함수에게 넘겨줄 매개변수];

 

스레드 수행 메서드

-(void)메서드명:(id)argument

{        

    작업 내용

}

-스레드 시작
[스레드객체 Start];

-스레드 중지
+(void)exit // 현재 실행중인 스레드 중지
-(void)cancel // 호출하는 인스턴스 스레드가 중지

ex)스레드로 메서드 수행
---------------------------------------------------------------
#import <Foundation/Foundation.h>
#import <stdlib.h>
@interface ThreadTest:NSObject
{
    NSThread *thread;
}     
-(void)setThread; // 스레드 생성하고 시작
-(void)Print:(id)argument; // 스레드가 수행할 메서드
@end

@implementation ThreadTest
-(void)setThread
{
//  -(id) initWithTarget:(id)스레드 수행 주체 selector:@selector(스레드로 수행할 메서드:) object:인수로 넘겨줄 오브젝트-스레드함수에게 넘겨줄 매개변수];
    thread = [[NSThread alloc] initWithTarget:self selector:@selector(Print:) object:nil];
               // 생성                                시작
    [thread start];
}
-(void)Print:(id)argument
// 비선점
{        
    NSLog(@"Hello World");               
}
@end

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    ThreadTest *Obj = [[ThreadTest alloc]init]; // 현재 스레드 생성 안됨
    if([NSThread isMultiThreaded] == YES)
     NSLog(@"현재 프로그램은 멀티 스레드 환경입니다.");
    else
     NSLog(@"현재 프로그램은 멀티 스레드 환경이 아닙니다.");
     [Obj setThread];
     if([NSThread isMultiThreaded] == YES)
     NSLog(@"현재 프로그램은 멀티 스레드 환경입니다.");
     else
     NSLog(@"현재 프로그램은 멀티 스레드 환경이 아닙니다.");
    [pool drain];   
    system("pause");    
    return 0;
}
---------------------------------------------------------------

//* 두개의 스레드 수행
---------------------------------------------------------------
#import <Foundation/Foundation.h>
#import <stdlib.h>
@interface ThreadTest:NSObject
{
    NSThread *thread1;
    NSThread *thread2;
}     
-(void)setThread;
-(void)Print:(id)argument;
@end

@implementation ThreadTest
-(void)setThread
{
    thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(Print:) object:nil];
    thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(Disp:) object:nil];
    [thread1 start];
    [thread2 start];
}
-(void)Print:(id)argument
{
         int i;                         
         for(i=0; i<10; i++)                
         {
                  NSLog(@"Hello World");
                  Sleep(1000);
         } 
         NSLog(@"Print 메서드 수행 종료");     
}
-(void)Disp:(id)argument
{
         int i;                         
         for(i=0; i<10; i++)                
         {
                  NSLog(@"Hi Objective-C");
                  Sleep(1000);                 
         } 
          NSLog(@"Disp 메서드 수행 종료");      
}
@end

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    ThreadTest *Obj = [[ThreadTest alloc]init];
    [Obj setThread];
    [pool drain];
    system("pause");
    return 0;
}
---------------------------------------------------------------

멀티스레드의 자원공유문제에러 => Mutex 에러 // Syncronize 하지 않아서 발생
                              // (Mutual Exclusion - 상호배제에러)

#import <Foundation/Foundation.h>
#import <stdlib.h>
@interface ThreadTest:NSObject
{
    NSThread *thread1;
    NSThread *thread2;
    int share;
}     
-(void)setThread;
-(void)Print:(id)argument;
@end

@implementation ThreadTest
-(void)setThread
{
    thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(Print:) object:nil];
    thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(Disp:) object:nil];
    [thread1 start];
    [thread2 start];
    share = 0;
}
-(void)Print:(id)argument
{
         int i;                                        
          for(i=0; i<10; i++)                
          {                
                  share --;
                  Sleep(100);
                  NSLog(@"감소 시킨 share 값: %i:", share);
          }       
}
-(void)Disp:(id)argument
{
         int i;
       
         for(i=0; i<10; i++)                
         {
                  share ++;
                  Sleep(100);
                  NSLog(@"증가 시킨 share 값: %i:", share);
         }         
}
@end

int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    ThreadTest *Obj = [[ThreadTest alloc]init];
    [Obj setThread];
    [pool drain];
    system("pause");
    return 0;
}
---------------------------------------------------------------

:
Posted by 에너지발전소
2010. 5. 27. 21:03

[15일차]일반 오브젝트 아카이브 Objective-C2010. 5. 27. 21:03

1. 일반 오브젝트 아카이브

일반 오브젝트를 아카이브 할 때는 NSCoding 프로토콜에 정의되어 있는 encodeWithCoder: initWithCoder: 메서드를 정의하면 됩니다.

 

메서드의 원형

-(void)encodeWithCoder:(NSCoder *)encoder

이 메서드의 안에서 encoder가 아카이브 할 실제 멤버들을 직접 인코딩하면 됩니다.

 

-(id) initWithCoder:(NSCoder *)decoder

이 메서드의 안에서 decoder가 언아카이브 할 실제 멤버들을 직접 디코딩하면 됩니다.




2. NSData를 이용한 아카이브

여러 개의 데이터를 아카이브 해야 하는 경우 NSData를 이용해서 이러한 작업을 수행할 수 있습니다.

이 때는 NSData를 이용해서 미리 영역을 설정한 후 이를 아카이브 클래스의 오브젝트에 연결한 후 이들을 아카이브 해나가면 됩니다.

------------------------------------------------------------
//Achive

#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSData.h>
@interface Test : NSObject<NSCoding>
{
  NSString * str;
  int n;
  float f;
}
-(void)setStr:(NSString *)msg;
-(NSString *)str;
-(void)setN:(int)temp;
-(int)n;  
-(void)setF:(float)temp;
-(float)f;                    
@end

@implementation Test
-(void)setStr:(NSString *)msg
{
  str = [NSString stringWithString:msg];
}
-(NSString *)str
{ return str; }
-(void)setN:(int)temp
{ n = temp; }
-(int)n
{ return n;}
-(void)setF:(float)temp
{ f = temp; }
-(float)f
{return f; }

-(void) encodeWithCoder:(NSCoder *)encoder
{
        [encoder encodeObject:str forKey:@"TestSrt"];
        [encoder encodeInt:n forKey:@"TestN"];
        [encoder encodeFloat:f forKey:@"TestF"];       
}

-(id) initWithCoder:(NSCoder *)decoder
{
    str =  [decoder decodeObjectForKey:@"TestSrt"];
     n =   [decoder decodeIntForKey:@"TestN"];
     f =   [decoder decodeFloatForKey:@"TestF"];       
}
@end

int main ()
{
 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 Test *Obj1 = [ [ Test alloc] init];
 Test *Obj2 = [ [ Test alloc] init];
 NSMutableData *dataArea; //nsData로 선언하면 Data변경이 안됨
 NSKeyedArchiver *archiver;
 
 [Obj1 setStr:@"Hello World"];
 [Obj1 setN: 111];
 [Obj1 setF: 11.1];
 
 [Obj2 setStr:@"Objective-C"];
 [Obj2 setN: 222];
 [Obj2 setF: 22.2];
 
 dataArea = [NSMutableData data]; // "data"는 생성자 , mutable 에서만 호출가능
 archiver = [[ NSKeyedArchiver alloc] initForWritingWithMutableData: dataArea];
 [archiver encodeObject:Obj1 forKey: @"Obj1"];
 [archiver encodeObject:Obj2 forKey: @"Obj2"];
 [archiver finishEncoding];
 
 if (( [ dataArea writeToFile:@"myArchive" atomically:YES ] ) == NO)
  NSLog(@"아카이빙 실패");
 
 [Obj1 release];
 [Obj2 release];
 [pool drain];
 system("pause");
    return 0;
}
------------------------------------------------------------
------------------------------------------------------------
//UnAchive
#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSCoder.h>
#import <Foundation/NSData.h>
@interface Test : NSObject<NSCoding>
{
  NSString * str;
  int n;
  float f;
}
-(void)setStr:(NSString *)msg;
-(NSString *)str;
-(void)setN:(int)temp;
-(int)n;  
-(void)setF:(float)temp;
-(float)f;                    
@end

@implementation Test
-(void)setStr:(NSString *)msg
{
  str = [NSString stringWithString:msg];
}
-(NSString *)str
{ return str; }
-(void)setN:(int)temp
{ n = temp; }
-(int)n
{ return n;}
-(void)setF:(float)temp
{ f = temp; }
-(float)f
{return f; }

-(void) encodeWithCoder:(NSCoder *)encoder
{
        [encoder encodeObject:str forKey:@"TestSrt"];
        [encoder encodeInt:n forKey:@"TestN"];
        [encoder encodeFloat:f forKey:@"TestF"];       
}

-(id) initWithCoder:(NSCoder *)decoder
{
    str =  [decoder decodeObjectForKey:@"TestSrt"];
     n =   [decoder decodeIntForKey:@"TestN"];
     f =   [decoder decodeFloatForKey:@"TestF"];       
}
@end

 

int main ()
{
   
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    NSData    *dataArea;
 NSKeyedUnarchiver *unarchiver;
 Test *Obj1, *Obj2;
 dataArea = [NSData dataWithContentsOfFile: @"myArchive"];
 if (dataArea == nil)
    {
  NSLog(@"읽어 오기 실패");
  return 0;
 }
 
 unarchiver = [[ NSKeyedUnarchiver alloc] initForReadingWithData: dataArea];
 Obj1 = [unarchiver decodeObjectForKey: @"Obj1"];
    Obj2 = [unarchiver decodeObjectForKey: @"Obj2"];
 
 [unarchiver finishDecoding];
 NSLog(@"Obj1의 데이터");
    NSLog(@"==============");
 NSLog(@"\n%@\n%i\n%g", [Obj1 str], [Obj1 n], [Obj1 f]);
    NSLog(@"==============");
 NSLog(@"Obj2의 데이터");
    NSLog(@"==============");
 NSLog(@"\n%@\n%i\n%g", [Obj2 str], [Obj2 n], [Obj2 f]);
    [unarchiver release];
    [pool drain];
 system("pause");
    return 0;   
}
------------------------------------------------------------
ex>archive를 이용한 오브젝트의 복사(깊은 복사)
#import <Foundation/Foundation.h>
int main ()
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 NSData    *data;
 NSMutableArray  *ar1 = [NSMutableArray arrayWithObjects:[NSMutableString stringWithString:@"1"], [NSMutableString stringWithString:@"2"],[NSMutableString stringWithString:@"3"],nil];
 NSMutableArray  *ar2;
 NSMutableString  *str;
 int i;
 data = [NSKeyedArchiver archivedDataWithRootObject: ar1];
 ar2 = [NSKeyedUnarchiver unarchiveObjectWithData: data];
 str = [ar1 objectAtIndex: 0];
 [str appendString: @"1"]; 
 NSLog(@"ar1: ");
 NSLog(@"=================");
 for(i=0; i<[ar1 count]; i++ )
  NSLog(@"%@", [ar1 objectAtIndex:i]);
 NSLog(@"=================");
 NSLog(@"ar2: ");
 NSLog(@"=================");
 for(i=0; i<[ar2 count]; i++ )
  NSLog(@"%@", [ar2 objectAtIndex:i]); 
    [pool drain];
    system("pause");
    return 0;
}
------------------------------------------------------------


** 예외처리

1. 예외처리를 위한 예약어

@try: Exceptions이 던져질 수 있는 block을 정의합니다.

@throw Exception object를 던진다.

@catch() @try bolck안에서 던져진 exception catch한다.

@finally @try block에서 Exceptions가 던져지던 아니던 수행되어질 block code를 정의한다.

모두 NSException.h에 정의되어 있습니다.


2. NSAssert (메서드 안에서 작성)
특정 조건을 만족하지 않는 경우 NSInternalInconsistencyException예외를 발생시켜 프로그램을 강제로 중단시키는 매크로함수

사용방법
NSAssert(만족해야 하는 조건, 출력할 문장);
         ==> 조건을 만족하지 않으면 Excception 발생시킨후 출력내용 출력

 

:
Posted by 에너지발전소
2010. 5. 26. 20:28

[14일차]객체의 복사 Objective-C2010. 5. 26. 20:28

* 얕은복사
int *p = (int *)malloc(4);
int *q = p;
*p = 10;
printf("%d",*p);
printf("%d",*q);
*p =20;
printf("%d",*q);


* 깊은복사
int*p=(int *)malloc(4);
*p=10;
int *q = (int*) malloc(4);
*q=*p;
printf("%d",*p);
printf("%d",*q);
*p=20;
printf("%d",*q);

ex)copy와 mutablecopy는 얕은복사
#import <foundation/NSObject.h>
#import <foundation/NSArray.h>
#import <foundation/NSString.h>
#import <foundation/NSAutorelease.h>
int main()
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    NSMutalbeArray * ar1 = [NSMutalbeArray arrayWithObjects:[NSMutableString:@"1"],[NSMutableString:@"2", [NSMutableString:@"3"],nil];
NSMutableArray *ar2;
NSMutalbeString *str;
int i;
NSLog(@"ar 1의 요소");
NSLog(@"--------");
for(i=0; i<[ar1 count];i++)
    NSLog(@"%d",[ar1 objectAtIndex: i]);
    ar2=[ar1 mutableCopy]; 
    str=[ar1 objectAtIndex:0];
    [str app;endString:@"1"];
    NSLog(@"---------");
    NSLog(@"ar2의 요소");
    NSLog(@"---------");
    for(i=0;i[ar2 count];i++)
        NSLog(@"%@",[ar2 objectAtIndex:i]);

[ar1 release];
[ar2release];
[pool drain];
system("pause");
return 0;
}

3. Copy의 구현
=>NSObject 클래스의 NSCopying프로토볼이 선언
=>NSObject 클래스에는 실제구현되어 있지 않음
   이 메서드는 내부적으로
  -(id)copyWithZone:(NSZone *)
                             //heap에 관련된 클래스0
                                메모리할당시 allocwinthzone: nose객체를 이용하면 비슷한 경험이 생김

따라서 copy메서드를 사용하고자 하는 경우 위의 메서드를 출현
:
Posted by 에너지발전소