본문 바로가기
  • 그냥 하자
iOS

Chap3-1. property와 synthesize

by Mash 2012. 3. 20.
반응형

이 글은 아래의 출처를 수정하여 작성한 글 임을 밝힌다. 
<출처 : http://wwwww.kr/30792> 

-  property 와 synthesize


- 메서드이지만 마치 변수처럼 사용할 수 있는 요소입니다.


- setter와 getter의 역할을 수행하는 메서드입니다. 

- 선언(클래스 선언 부에서 작성 - 메서드 선언하는 영역)
  @property (특성나열) 자료형 변수명;

- 구현(클래스 구현부에서 작성 - 아무 곳이나 가능)
  @synthesize 변수명;

- 위 처럼 선언과 구현을 하면 getter와 setter메서드가 구현 된 것으로 간주 합니다.


1. property 

 - getter 와 setter의 선언을 대신할 수 있는 지시어
 - 형식 :
   @property (특성 나열) 변수 선언;



2. synthesize

 - getter 와 setter 의 구현을 대체
 - 형식 : 
   @synthesize 변수명;



3. 프로퍼티 특성

 @property(setter|getter = 메서드명) 자료형 변수명;
 메서드를 직접 작성한 경우 연결할 때 사용
 

 @property(readonly|readwrite) 자료형 변수명;
 읽기 전용과 읽기와 쓰기 가능 프로퍼티 지정 - 기본은 readwrite
 

 @property(assign|retain|copy) 자료형 변수명;
 멤버변수가 객체인 경우 대입방법에 대한 지정 - 객체인 경우 필수
 

 @property(nonatomic) 자료형 변수형;
 멀티 스레드 환경에서 상호 배제 코드를 삽입할 것인지 여부
 

 @synthesize 별명 = 원래이름;
 변수를 별명으로  synthesize
 

 1) atomic | nonatomic
 atomic : 상호배제코드 포함
 nonatomic : 상호배제코드 미포함, 속도가 향상됨, 아이폰SDK 에서는 대부분 이것만 사용

 2) readonly | realwrite 
 readonly : getter만 있음. 값을 넣을 수 없음.
 readwrite : getter 와 setter 둘 다 존재.

 3) setter | getter = 메서드명
 getter : 데이터 타입이 BOOL인 경우 is 삽입을 위하여 사용

 4) assign | retain | copy
 객체(참조형)인 경우 필수

 5) @synthesize 별명 = 원래이름;

 

int *p = (int *) malloc (4);
*p=10;
int *q = p; // assign : 단순하게 대입
int *q = (int *) malloc(4); //copy - 단점 : 메모리 공간 사용이 많다.
*q = *p;

01.1. 이전 프로젝트의 Test.h 파일의 선언 부 수정
02.#import <Foundation/Foundation.h>
03.@interface Test : NSObject {
04.int value;
05.}
06.- (id)init:(int)a;
07.- (void)Disp;
08.- (void)add:(int)first:(int)second;
09.- (void)addWithFirst:(int)first withSecond:(int)second;
10.//- (int)value;
11.//- (void)setValue:(int)n;
12.@property int value;
13.@end
01.2. 이전 프로젝트의 Test.m 파일의 메서드 구현 부분 수정
02./*
03.- (int)value
04.{
05.return value;
06.}
07.- (void)setValue:(int)n
08.{
09.value = n;
10.}
11.*/
12.@synthesize value;
01.3. ClassTest.m 파일의 main 메서드 수정
02.#import "Test.h"
03.int main (int argc, const char * argv[])
04.{
05.NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
06.Test *obj;
07.obj = [Test new];
08.[obj setValue:10];
09.NSLog(@"value의getter:%d", [obj value]);
10.[pool drain];
11.return 0;
12.}

01.1. 이전 프로젝트의 Test.h 파일의 선언 부 수정
02.#import <Foundation/Foundation.h>
03.@interface Test : NSObject
04.{
05.int value;
06.}
07.- (id)init:(int)a;
08.- (void)Disp;
09.- (void)add:(int)first:(int)second;
10.- (void)addWithFirst:(int)first withSecond:(int)second;
11.//@property int value;
12.@property (nonatomic, readonly)int value;
13.@end


4. .(dot)을 이용한 접근 : 프로퍼티로 지정된 getter와 setter는  [ ]를 생략하고 .을 이용해서 접근할 수 있다.
 getter와 setter의 이름을 getter이름 하나로 사용 : = 의 왼쪽이면 자동적으로 setter
 여러번 연속해서 사용이 가능하다.
 setter의 접근은 객체명.변수명=값; 형태가 된다.
 변수는 화살표, 프로퍼티만 .쩜!!

01.1. 이전 프로젝트의 Test.h 파일의 선언 부 수정
02.#import <Foundation/Foundation.h>
03.@interface Test : NSObject
04.{
05.int value;
06.}
07.- (id)init:(int)a;
08.- (void)Disp;
09.- (void)add:(int)first:(int)second;
10.- (void)addWithFirst:(int)first withSecond:(int)second;
11.@property (nonatomic)int value;
12.@end
01.2. ClassTest.m 파일의 main 메서드 수정
02.#import "Test.h"
03.int main (int argc, const char * argv[])
04.{
05.NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
06.Test *obj;
07.obj = [Test new];
08.obj.value = 10;
09.NSLog(@"value의getter:%d", obj.value);
10.[pool drain];
11.return 0;
12.}

 

=================================================================================================

const

=================================================================================================

- 변수를 상수화 시켜주는 예약어
- 일반 포인터 변수 앞에 사용되면 가리키는 자체는 변경할 수 있지만 내용은 변경 불가능
- 일반 변수에 사용되는 경우에는 readonly로 동작
- 일반적으로 클래스의 구현부에서 사용
- 멤버변수에 const가 사용되는 경우 무조건 0으로 사용해야 함
===========================
char ch[]="Hello";
const char *str = "Hello";

ch[1]='k'; // e를 k로 변경 가능.
str[1]='k'; // error. 변경 불가.
===========================

 

=================================================================================================

extern 변수

=================================================================================================

- 서로 다른 파일 간에 변수를 공유할 수 있는 개념
- 서로 다른 파일 간에도 변수를 공유해서 메세지를 주고 받을 수 있다.
- 선언 한 후 사용하고자 하는 곳에서 재정의해서 사용해아 함.
- 아이폰에서는 잘 사용하지 않는다.
1) 파일과 파일사이의 공유
2) 프로그램 사이의 데이터 공유 => 아이폰에서 필요없음

아이폰의 앱은 AppDelegate객체에서 출발 

=================================================================================================

  토탈 예제

=================================================================================================

 

001.//day3.m
002.#import <Foundation/Foundation.h>
003.//다른 파일에 있는 선언문을 사용하고자 하는 경우에는 헤더파일이 import되어야 합니다.
004.//Test 라는 클래스의 사용을 위해서 import
005.//SDK가 제공해주는 클래스를 사용할 때는 < > 안에 헤더파일 이름을 기재해야 하고
006.//자신이 만든 클래스를 사용하고자 할 경우에는 " " 안에 기재해야 합니다.
007. 
008.#import "test.h"
009.int main (int argc, const char * argv[]) {
010.NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
011.//alloc과 init으로 생성 - 정적 타이핑(변수 선언할 때 자료형을 기재)
012.Test * Obj1 = [[Test alloc]init];
013.NSLog(@"%@", Obj1);
014. 
015.//Obj1 이 print라는 메서드를 호출
016.[Obj1 print]; // -가 붙어있으므로 [Test print]; 라고 하면 안됨.
017. 
018.//클래스 메서드이므로 Obj1이 호출할 수 없다.
019.[Test disp]; //+가 붙어있으므로 오른쪽처럼 하면 안된다. //[Obj1 disp];
020. 
021.//정수 매개변수 1개를 갖는 printWithInt를 호출
022.[Obj1 printWithInt : 10];
023. 
024.//호출 시 의미까지 호출해야 함
025.int n;
026.[Obj1 add:10 :20 :n];
027.[Obj1 addWithFirst:10 withSecond:20 saveWithResult:n];
028. 
029.//value에 프로퍼티가 지정되어 있으므로 [] 대센이 . 을 이용해서 getter와 setter를 호출할 수 있다.
030.//getter와 setter모두 getter이름만으로 접근하며 =의 오른쪽에 사용되면 자동적으로 setter가 된다.
031.//셋터(왼쪽) = 겟터(오른쪽)
032./*
033.[Obj1 setValue:50];
034.NSLog(@"value : %d", [Obj1 value]);
035.*/
036.Obj1.value=50;
037.NSLog(@"value : %d", Obj1.value);
038. 
039.//new 로 생성 - 동적 타이핑(변수 선언할 때 자료형을 기재하지 않음)
040./*
041.id Obj2 = [Test new];
042.NSLog(@"%@", Obj2);
043.*/
044. 
045.[pool drain];
046.return 0;
047.}
048.//
049.//  Test.h
050.//  ClassTest
051.//
052.//  Created by iMac_23 on 10. 11. 5..
053.//  Copyright 2010 __MyCompanyName__. All rights reserved.
054.//
055. 
056.#import <Foundation/Foundation.h>
057.@interface Test : NSObject {
058. 
059.int value;
060.}
061.@property int value;
062.//@propery (readonly) int value ; <- 읽기전용으로 변경하는 방법. 여기선 이렇게 하면 오류 남.
063./* getter와 setter
064.- (int)value;
065.- (void)setValue : (int)temp;
066.//property : getter 와 setter의 선언을 대체
067.//형식 : @property (특성 나열) 변수 선언;
068.*/
069. 
070.- (void)print; // -는 멤버,객체
071.+ (void)disp; // +는 클래스
072. 
073.- (void)printWithInt:(int)n;
074. 
075.- (void)add:(int)first:(int)second:(int)result;
076.- (void)addWithFirst:(int)first withSecond:(int)second saveWithResult:(int)result;
077.@end
078.//
079.//  Test.m
080.//  ClassTest
081.//
082.//  Created by iMac_23 on 10. 11. 5..
083.//  Copyright 2010 __MyCompanyName__. All rights reserved.
084.//
085.#import "Test.h"
086.@implementation Test
087./*
088.//변수의 getter는 변수만 리턴하면 됨
089.- (int)value
090.{
091.return value;
092.}
093.//변수의 setter는 매개변수를 변수에 대입하면 됨
094.- (void)setValue:(int)temp
095.{
096.value = temp;
097.}
098.*/
099.@synthesize value;
100./* synthesize : getter 와 setter의 구현을 대체
101.형식 : @synthesize 변수명; */
102.- (void) print
103.{
104.NSLog(@"Hello");
105.}
106.+ (void) disp
107.{
108.NSLog(@"Hi");
109.}
110.- (void) printWithInt:(int)n
111.{
112.NSLog(@"n:%d",n);
113.}
114.- (void)add:(int)first:(int)second:(int)result
115.{
116.result = first + second;
117.NSLog(@"%d", result);
118.}
119.- (void)addWithFirst:(int)first withSecond:(int)second saveWithResult:(int)result
120.{
121.result = first + second;
122.NSLog(@"%d", result);
123.}
124.@end



 계속....


반응형