본문 바로가기

개발도구/iOS - 아이폰 개발

[ios] 값 주고 받기 - 값 넘기기

펌 - http://whitegom.tistory.com/11

1) NSuserDefaults

불러오기

[[NSuserDefaults standardUserDefaults] valueForKey:(NSString *)];

ex) 

[NSUserDefaults standardUserDefaults]valueForKey:@"Key"];
NSString *receiveData = 
[NSUserDefaults standardUserDefaults]valueForKey:@"Key"];


저장

[[NSuserDefaults standardUserDefaults] setValue:(id) forKey:(NSString *)];

ex)
NSString *sendData = @"send"; 

[[NSUserDefaults standardUserDefaultssetValue:sendData forKey:@"testKey"]

2) NSNotificationCenter

등록 (보내기)

//보낼 딕셔너리를 만들고 키값을 입력한다
 
NSDictionary *dic = [NSDictionary dictionaryWithObject:textData.text forKey:@"InputText"];

//노티피케이션 센터를 등록한다.
 NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
//key값과 딕셔너리 그리고 노티피케이션의 이름을 함께 등록한다.
[nc postNotificationName:@"saveTextFieldText" object:self userInfo:dic]; 



받기 (옵저버)

//노티피케이션센터를 등록한다.
 
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
//
saveTextFieldText메시지가 발생 시 작동하며  셀렉터는 함수를 사용한다 viewText는 아래와 같다.
 [nc addObserver:self selector:@selector(viewText:

name:@"saveTextFieldText" object:nil];

-(void) viewText:(NSNotification *)noText{
    // 딕셔너리에 대한 정보를 받고 키값으로 값을 찾아 등록한다.
    NSString *ncText = [[[noText userInfoobjectForKey:@"InputText"retain];
    NSLog("ncText = @%",ncText);

3) Delegate

선언 .h 파일 (업케스팅이라고 생각하시면 됩니다.)

#import <UIKit/UIKit.h>

//델리게이트를 사용하기 위한 프로토콜 선언
@protocol
 SendDataDelegate;

@interface SendData : UIViewController {

   //프로토콜을 따르는 id값을 선언
     
id<SendDataDelegate>delegate;

}
//다른 클래스에서도 접근 하기 때문에 프로퍼티로 선언해주어야 합니다. 당연히 .m파일에 @synthesize delegate; 추가 
@property (nonatomicassignid<SendDataDelegate>delegate;
@end

@protocol SendDataDelegate <NSObject>;
@required
//프로퍼티를-(void)SendNumber:(NSInteger)nBer1 withNum:(NSInteger)nBer2;
@end


.m 파일


@synthesize delegate;
//델리게이트를 사용할 위치에 사용합니다. number1과 number2는 호출부로 넘어가서 사용됩니다.
 [self.delegate SendNumber:number1 withNum:number2]; 

//프로토콜이 있는 해더파일을 임포트 시켜줍니다.
#import 
"SendData.h"

//SendDataDelegate의 프로토콜을 따르겠다는 선언을 합니다.@interface
 Coupon : UIViewController<SendDataDelegate>{
 
    SendData *sd;
}//객체를 초기화 하고 델리게이트를 호출하도록 합니다.
 sd = [[SendData alloc]initWithNibName:@"SendData" bundle:nil];
 sd.delegate = self; 

//호출부를 구현 합니다.
-(void)SendNumber:(NSInteger)nBer1 withNum:(NSInte

ger)nBer2{

    NSInteger getNber = nBer1 - nBer2;
    NSLog(@"%d",getNber);



4) NibName

받는 부분

//.h 파일  
@interface
 ReceiveData : UIViewController {
 
    NSString *test;
}
@property (nonatomicassignNSString *test;@end  

//.m파일  
@synthesize test; 


보내는 부분

//.h파일 임포트하고 객체 생성후 값을 넣어준다.
#import 
"ReceiveData.h"   @interface SendData : UIViewControlle{
      ReceiveData *reData;}
//.m파일 필요한 부분에 적용시킨다. 
 reData
 = [[ReceiveData alloc]initWithNibName:@"ReceiveData" bundle:nil];
 reData
.test = @"test good";