'공지사항'에 해당되는 글 107건
- 2020.04.14 :: [PHP] PHP 함수의 인수 배우보자!!!
- 2020.04.14 :: [PHP] PHP 문자 N 문자를 연결해보자!
- 2020.04.14 :: [PHP] PHP 함수 생성 및 호출
- 2020.04.14 :: [PHP] PHP 다운로드
- 2020.04.14 :: [Olly_Dbg] 올리디버거 다운로드 (1.10Ver)
- 2020.04.14 :: [Ruby] 루비 다운로드
- 2020.04.14 :: [Objective-C] 기초배우기 (4)
- 2020.04.14 :: [Objective-C] 기초배우기 (3)
[PHP]함수의 인수
함수 안에서 사용하는 값을 함수 밖에서 전달할 수 있는데 이 값을 인수라고 한다.
-예
<?php
function check($age) {
$result = (20 <= $age)?"프로":"그래밍";
print $result."입니다.";
}
check(19);
?>
-결과
프로그래밍
인수가 지정되지 않은 경우(에러가 발생한다.)
- 예
<?php
function check($age) {
$result = (20 <= $age)?"프로":"그래밍";
print $result."입니다.";
}
check();
?>
- 결과(에러 발생)
Fatal error: Uncaught ArgumentCountError: Too fewargumenC:/ xampp/hydocs/for:php:
2 Stack trace: #0 C:xampp/hidocs/for
인수에 값이 없는 경우 에러가 발생하므로 인수의 기본값을 사용한다.
-예
<?php
function check($age=19) {
$result = (20 <= $age)?"프로":"그래밍";
print $result."입니다.";
}
check();
?>
- 결과(에러가 발생하지 않았다.)
프로그래밍
<?php
function test($x1, $x2)(
echo '*'.$x1.$x2.'*';
)
test('핵','커');
?>
결과는 *핵커*
'PHP' 카테고리의 다른 글
[PHP] PHP 문자 N 문자를 연결해보자! (0) | 2020.04.14 |
---|---|
[PHP] PHP 함수 생성 및 호출 (0) | 2020.04.14 |
[PHP] PHP 다운로드 (0) | 2020.04.14 |
[PHP] 시작,종류,태그,변수,저장확정자 (0) | 2020.04.11 |
[PHP]문자와 문자를 연결하기
php에서는 문자와 문자를 연결시 + 대신에 .를 사용한다.
-입력
<?php
echo "*"."아이유";
?>
-출력
아이유
html을 포함한 경우
-줄바꿈이 가능하다.
-입력
<?php
echo "*"."아이"."</br>"."유2";
?>
-출력
결과
아이유
입력1
<?
$test = "너 ";
$test.= "랑";
$test.= "나";
print $test;
?>
결과
너 랑 나
'PHP' 카테고리의 다른 글
[PHP] PHP 함수의 인수 배우보자!!! (0) | 2020.04.14 |
---|---|
[PHP] PHP 함수 생성 및 호출 (0) | 2020.04.14 |
[PHP] PHP 다운로드 (0) | 2020.04.14 |
[PHP] 시작,종류,태그,변수,저장확정자 (0) | 2020.04.11 |
[PHP]함수 생성 및 호출
다음은 모두 같은 의미이다.
- 작은 프로그램의 모음
- 서브루틴
- 사용자 정의 함수
사용자 정의 함수를 사용하면 같은 내용을 여러 번 사용할 때 간단히 함수를 불러오면 되서 편리하다.
정의
- function 함수명() {
처리 내용;
}
사용
- 함수명();
* 함수의 정의와 함수의 사용 순서는 상관없다.
예
<?php
function copyright() {
print "<font size=7>";
print "copyright all right reserved";
print "</font>";
}
copyright();
?>
<?php
fuction test()(
echo 1;
)
test();
?>
함수 실행 예1
<?php
test($x)(
echo $x;
)
test('hello world');
?>
함수 실행 예2
<?php
test($x)(
echo $x;
)
test('hello world');
test('hello jeju');
?>
함수 실행 예3
<?php
test($x)(
echo $x;
)
test('hello');
test('mr my);
test('yesterday);
?>
'PHP' 카테고리의 다른 글
[PHP] PHP 함수의 인수 배우보자!!! (0) | 2020.04.14 |
---|---|
[PHP] PHP 문자 N 문자를 연결해보자! (0) | 2020.04.14 |
[PHP] PHP 다운로드 (0) | 2020.04.14 |
[PHP] 시작,종류,태그,변수,저장확정자 (0) | 2020.04.11 |
'PHP' 카테고리의 다른 글
[PHP] PHP 함수의 인수 배우보자!!! (0) | 2020.04.14 |
---|---|
[PHP] PHP 문자 N 문자를 연결해보자! (0) | 2020.04.14 |
[PHP] PHP 함수 생성 및 호출 (0) | 2020.04.14 |
[PHP] 시작,종류,태그,변수,저장확정자 (0) | 2020.04.11 |
'Olly_Dbg' 카테고리의 다른 글
[올리디버거] 단축키 알아보자 (0) | 2020.04.10 |
---|
9.파운데이션 프레임워크
9-1.루트 클래스
NSObject는 Objective-C의 클래스가 가져야 할 가장 기본적인 기능(메모리 관리, 객체 식별 등)을 제공하며,모든 클래스는 NSObject를 직접 혹은 간접적으로 상속함으로써 그 기능들을 사용할 수 있게된다. 사용자가 직접 구현하는 클래스도 이를 위해 NSObject를 상속하는 것을 절대 잊지말아야한다.
9-2.문자열 관련 클래스
9-2-1.NSString
유니코드 방식으로 문자열을 다루는 기능을 제공하는 클래스,. 파운데이션 프레임워크에서 가장 많이 사용되는 클래스
-기본사용방법 : 문자열 앞에 항상 '@'를 붙여주어야한다. NSString *string = @"string test";
-포맷표현 방식 : 다른언어의 %s가 아니라 %@사용한다. 나머지 타입은 같다(%d,%f,%u)
NSString *string1 = [[NSString alloc]initWithFormat:@"%@",@"string"];
NSStirng *string2 =[NSString stringWithString:@"string"];
-생성 메소드 : 클래스 메소드는 alloc 또는 copy로 시작하는 이름을 갖지 않으므로 사용이 끝난 후 release할 필요없다.
인스턴스 메소드들은 alloc 메소드를 이용하여 생성되므로, 사용이 끝난 후에는 반드시 release를 호출해야한다.
//빈 문자열을 가지는 객체를 생성하여 반환
+(id)string
//주어진 문자열을 가지는 객체를 생성하여 반환
+(id)stringWithFormat:(NSString *)format, …
+(id)stringWithString:(NSString *)aString;
//위 메소드들의 인스턴스 메소드 형태, 기능은 동일
-(id)initWithFormat:(NSString *)format …
-(id)initWithString:(NSString *)aString
//사용예
NSString *string1 = [NSString string];
NSString *string2 = [NSString stringWithFormat:@"String: %@", @"Test"];
NSString *string3 = [NSString stringWithString:@"String"];
NSString *string4 = [[NSString alloc] initWithFormat:@"String : %@",@"Test"];
NSString *string5 = [[NSString alloc] initWithString:@"String"];
-결합메소드
//현재 문자열과 주어진 문자열을 결합하여 반환
-(NSString *)stringByAppendingFormat:(NSSting *)format …
-(NSString *)stringByAppendingString:(NSString *)aString
//사용예
NSString *string1 = @"Hello"
NSString *string2 = [stirng1 stringByAppendingFormat:@"%@",@"World"];
NSString *string3 = [stirng1 stringByAppendingString:@" World"];
-분리 메소드
//현재 문자열을 검사하여 주어진 문자열이 나타낼 때마다 문자열 분리
-(NSArray *)componentsSeparatedByString:(NSString *)separator
//현재 문자열의 주어진 위치 이후 문자열 반환
-(NSString *)substringFromIndex:(NSUInteger)anIndex
//현재 문자열의 주어진 위치까지의 문자열 반환
-(NSString *)substringToIndex:(NSUInteger)anIndex
//사용예
NSString *string1 = @"String1, String2, String3";
NSArray *iterms =[string1 componentsSeparatedByString:@". "];
//ite는 :{@"String1", @"String2", @"String2"}
NSString *string2 =@"String";
NSString *string3 =[string2 substringFromIndex:3];
NSString *string4 =[string2 substringToIndex:3];
//string 2: @"ing" string 4:@"str"
-값 변환 메소드
//현재 문자열에 해당하는 정수값 반환
-(int)intValue
//현재 문자열에 해당하는 실수값 반환
-(float)floatValue
-(double)doubleValue
//사용예
NSString *string1 =@"5";
int intValue =[string1 intValue]; //intValue : 5
NSString *string2 =@"2.34";
float floatValue = [string2 floatValue]; //2.34
double double Value = [string2 doubleValue]; //2.34
-비교 메소드
//현재 문자열이 주어진 문자열로 시작하는지 검사
-(BOOL)hasPrefix:(NSString *)aString
//현재 문자열이 주어진 문자열로 끝나는지 검사
-(BOOL)hasSuffix:(NSString *)aString
//현재의 문자열이 주어진 문자열과 동일하지 검사
-(BOOL)isEqualToString:(NSString *)aString
//사용예
NSString *string1 = @"Hello World!";
BOOL value1 = [string1 hasPrefix:@"Hel"];
BOOL value2 = [string1 hasSuffix:@"orld"]; //value1,value2 :YES
BOOL value3 = [string1 isEaualToString:@"Hello World!"]; //value3 :YES
-기타 메소드
//문자열의 길이를 반환
-(NSUInteger)length
//문자열읮 ㅜ어진 위치에 해당하는 문자를 반환
-(unichar)characterAtIndexLNSUInteger)index
//사용예
NSString *string = @"String";
int length = [string length]; //length :6
unichar value = [string characterAtIndex:3]; //value : i
9-2-2.NSMutableString
NSString 클래스를 상속하는 자식 클래스, 문자열을 한번 할당하면 변경할 수 없는 NSString과는 달리 수정할 수 있다는 것이 장점, 참고로 파운데이션 프레임워크 클래스 중에서 이름에 Nutable이 포함된 클래스 (NSMutableArray, NSMutableDictionary 등)는 값을 수정할 수 있는 클래스다,.
//주어진 문자열을 현재의 문자열과 결합
-(void)appendFormat:(NSString *)format ..
-(void)appendFormat:(NSString *)aString
//주어진 문자열을 현재 문자열의 주어진 위치에 사입
-(void)insertString:(NSString *)aString atIndex:(NSUInteger)anIndex;
//현재의 문자열을 주어진 문자열로 대체
-(void)setString:(NSString *)aString
//사용예
NSMutableString *string. = [NSmutableString stringWithString:@"Hello"]; //String :@"Hello"
[string appendFormat:@"%@",@"Wor"]; //String :@"Hellowor"
[string appendString:@"ld!"] //string: @"Helloworld!"
[string insertString:@" " atIndex:5]; //string: @"Hello world!"
[string setString:@"Bye World!"]; //string: @"Bye World!"
9-3.객체 집합 관련 클래스
NSArray : 순서가 있는 객체 리스트를 관리
NSDictionary : 키 – 값 형태의 객체 리스트를 관리
NSSet : 순서가 없는 객체 리스트를 관리
위는 할당된 내용을 수정할 수 없는 클래스지만. 이들 클래스 이름에 Mutable이 들어간 MSMutableArray, NSMutableDictionary, NSMutableSet는 수정할수 있는 클래스이다.
9-3-1.NSArray
-생성메소드
//사용예
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = @"a string";
// +(id)arrayWithObjects : 주어진 객체들을 포함하는 객체를 생성하여 반환
NSArray *array1 = [NSArray arrayWithObjects:aData, avalue, aString, nil]; //마지막은 반드시 nil을 전달
// -(id)initWithObjects : arrayWithObjects의 인스턴스 메소드 형태, 기능은 동일
NSArray *array2 = [[NSArray alloc]initWithObjects:aData, aValue, aString, nil]; //마지막은 반드시 nil을 전달
//+(id)arrayWithArray: 주어진 배열 내의 인자들을 포함하는 객체를 생성하여 반환
NSArray *array3 = [NSArray arrayWithArray: array1];
//-(id) initWithArray : +arrayWithArray의 인스턴스 메소드 형태 기능은 동일
NSArray *array4 = [[NSArray alloc] initWithArray: array1];
주요메소드
NSString *item1 = @"1", *item2 = @"2", *item3=@"3";
NSArray *array = [NSArray arrayWithObjects: item1, item2, item3, nil]; //array :{item1, item2, item3}
//주어진 배열 내의 인자의 수를 반환
int cout : [array count]; //count :3
//주어진 인덱스의 객체를 반환
NSString *string = [array objectAtIndex:1]; //string :@"2"
//주어진 객체의 배열 내의 인덱스를 반환
NSUInteger index = [array indexOfbject :item3]; //index:2
9-3-2.NSMutabelArray
NSString *item1 = @"1", *item2 = @"2", *item3=@"3", *item4=@"4";
NSMutableArray *array =[NSMutableArray arrayWithObjects: item1, item2, item3, nil]; //array :{item1, item2, item3}
//주어진 인자를 지정된 위치에 삽입한다.
[array insertObject:item4 atIndex:2]; ////array :{item1, item2,item4, item3}
//지정된 위치의 인자를 삭제한다.
[array removeObjectAtIndex:3]; ////array :{item1, item2,item4}
//주어진 인자를 배열 끝에 추가한다.
[array addObject:item3]; // array :{item1, item2,item4,item3}
//마지막 인자를 삭제한다.
[array removeLastObject]; // array :{item1, item2,item4}
//현재 배열의 지정된 위치의 객체를 주어진 객체로 대체한다.
[array replaceObjectAtIndex:2, withObject:item3]; // array :{item1, item2,item3}
9-3-3.NSDictionary –stl의 map
-생성메소드
//+(id) dictionaryWithObjectsAndKeys: 주어진 객체, 키 값으로부터 객체를 생성반환
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2",nil];
//-(id) initWithdictionaryWithObjectsAndKeys:+(id) dictionaryWithObjectsAndKeys의 인스턴스 메소드 형태
NSDictionary *dict2 = [[NSDictionary alloc] initWithdictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2",nil];
-주요메소드
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Chris", @"name", @"programmer", @"job",nil]; //dirct :{@"job" : @"programmer", @"name :@"Chris"}
//dictionary에 있는 객체의 수를 반환
NSUInteger count = [dict count]; //count :2;
//dictionary에 있는 모든 키 값들을 반환
NSArray *keys= [dict allKeys]; //Keys:{@"job",@"name"};
//dictionary에 있는 모든 객체들을 반환
NSArray *values = [dict allValues]; values :{@"programmer",@"Chris"}
//주어진 키 값을 갖는 객체를 반환
NSString *string = [dict objectForKey:@"name"]; //string : @"Chris"
9-3-4.NSMutableDictionary
NSMutableDictionary *dict =[NSMutableDictionary dictionary]; //Dict: { }
//주어진 객체와 키 조합을 추가한다.
[dict setObject:@"Chris" forKey:@"name"]; //dict:{@name: @"chris"}
[dict setObject:@"programmer" forKey:@"job"]; //dict: {@"job": @"programmer", @"name" : @"Chris"}
//주어진 객체와 키 조합을 삭제
[dict removeObjectForKey:@"name"]; //dict : {@"job" : "programmer"};
//모든 객체-키 조합 삭제
[dict removeAllObjects];//dict:{ }
9-3-5.NSSet –NSArray와 달리 순서가 없다.
-생성메소드
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = @"a string";
//주어진 객체들을 포함하는 객체를 생성하여 반환
NSSet "mySet =[NSSet setWithObjects:aDate, aValue, aString, nil];
// NSSet "mySet =[[NSSet alloc]initWithObjects:aDate, aValue, aString, nil];
-주요메소드
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *name = @"Chris";
NSSet *mySet =[NSSet setWithObjects: date, value, name, nil]; //mySet :{value, name, date}
//NSSet 에 들어있는 오브젝트 객체 개수
NSUInteger count =[mySet count]; //count :3
//NSSet에 들어있는 모든 오브젝트 객체 반환
NSArray *array1 = [mySet allObjects]; // array1 : {value, name, date;
//NSSet 내에 주어진 객체가 존재하는지 검사하여 결과 반환
BOOL result = [mySet containsObject:@"Chris"]; //result :YES
9-3-6 NSMutableSet
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *name = @"Chris", *job = @"programmer";
NSMutableSet *mySet =[NSMutableSet setWithObjects: date, value, name, nil]; //mySet :{value, name, date}
//set에 주어진 객체를 추가
[mySet addObject:job]; //mySet :{job, value, name, date}
//set에 주어진 객체 삭제
[mySet removeObject:@"Chris"]; //mySet :{job, date,value}
//set의 모든 객체 삭제
[mySet removeAllObjects]; //mySet: {}
9-3-7 객체 탐색
-객체를 탐색하는 예
NSArray *array = [NSArray arrayWithObjects:@"One",@"Two", @"Three", @"Four", nil];
NSString *item = nil;
for( item in array){
if([item isEqualToString:@"Three"]){
break;
}
}
-NSEnumerator를 사용하는 방법
NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @Three", @"Four", @nil];
NSString *item = nil;
NSEnumerator *enumerator = [array objectEnumerator];
while(item = [enumerator nextObject]){
if( [item isEqualToString:@"Three"]){
break;
}
}
NSEnumerator 사용하면 좋은예
NSArray의 경우 reverseEnumerator 메소드를 이용하여 객체를 역순으로 탐색 할수 있다.
objectEnumerator 대신에 reverseEnumerator 메소드를 호출하면 된다.
NSDictionary의 경우 NSEnumerator를 이용하면 키 값뿐 아니라 객체도 탐색할 수 있다. 키 값을 탐색할때는 KeyEnumerator 메소드, 객체 값을 탐색할때는 objectEnumerator를 이용하면 된다
9-4. 값(정수 및 실수)표현 관련 클래스
9-4-1.NSNumber
NSValue 클래스를 상속하는 자식 클래스, BOOL, char, int, float와 double 등 각종 값을 설정하고 반환하는 기능을 수행한다.
NSNumber *boolNumber = [NSNumber numberWithBool:YES];
NSNumber *intNumber = [NSNumber numberWithInt:23];
NSNumber *doubleNumber = [NSNumber numberWithDouble:23.46];
BOOL value1 = [boolNumber boolValue];
int value2 = [intNumber intValue];
double value3 = [doubleNumber doubleValue];
//값비교
NSNumber *intNumber = [NSNumber numberWithInt:23];
NSNumber *floatNumber = [NSNumber numberWithFloat:3.45];
NSString *string1 = [intNumber stringValue]; //string1 : 23
if(NSOrderedAscending == [intNumber compare:floatNumber]{
…
}
BOOL equality = [intNumber isEqualToNumber:floatNumber];
//compare:메소드는 kemdarhk 같은 반환값을 가지게된다.
NSOrderedAscending :현재 값보다 주어진 값이 클경우
NSOrderedDescending :현재 값보다 주어진 값이 작은경우
NSOrderedSame :현재 값과 주어진 값이 같은
'Objective_C' 카테고리의 다른 글
[Objective-C] 기초배우기 (3) (0) | 2020.04.14 |
---|---|
[Objective-C] 기초배우기 (2) (0) | 2020.04.14 |
[Obejective-C] 기초배우기 (1) (0) | 2020.04.13 |
7.프로토콜
특정 객체에 변화가 일어나면 혹은 어떤 특별한 의미를 가지는 시점에 도달하면 해당 객체로부터 이에 대한 알림 서비스를 받고 싶을경우 '프로토콜'를 사용한다.
프로토콜을 사용하면 객체로부터 콜백 메소드의 형태로 알림 서비스를 받을 수 있다.
1.프로토콜을 선언하는 brush 클래스가 구현되는 방식
//헤더파일
@protocol 프로토콜 이름; //(1) 프로토콜을 선언하는 부분
@interface 클래스 이름: 부모 클래스 이름{
id<프로토콜 이름> delegate; //(2)프로토콜을 사용하고자 하는 클래스 인스턴스의 포인터
…
}
@property (nonatomic, retain) id<프로토콜 이름> delegate;
//프로토콜을 사용하는 메소드 //(3) 프로토콜을 사용하는 메소드를 선언한다.
@end
@protocol 프로토콜 이름 <타 프로토콜 이름> //(4)@protocol에서 @end까지 프로토콜을 정의하는 부분
@required //(5)required에는 반드시 정의해야하는 메소드(기본)
메소드 선언 리스트
@optional //(5)optional에는 반드시 정의할 필요는 없는 메소드를 선언
메소드 선언 리스트
@end
//소스파일
#import "헤더 파일"
@implementation
@synthesize delegate;
...
프로토콜에서 선언된 메소드를 호출하는 메소드 정의 //(6) 프로토콜에서 선언된 메소드를 정의한다.
…
@end
(2)프로토콜을 사용하고자 하는 클래스 인스턴스의 포인터를 저장하는 부분, 이 값을 정의하지 않으면 프로토콜 메소드를 호출할 방법이 없으므로 프로토콜을 사용하는 클래스 인스턴스에서 반드시 설정해야한다.
(3) 프로토콜을 사용하는 메소드를 선언한다. 당연한 이야기지만 어느 메소드가 프로토콜 내의 어느 메소드를 호출해야 한다는 내용은 정해져 있지 않다. 인터페이스 내의 어떠한 메소드라도 프로토콜 내에 선언되어 있는 메소드를 호출할 수 있다. 즉, 적절한 메소드에서 필요한 시점에 호출해주면되는 것이다.
(4)@protocol에서 @end까지 프로토콜을 정의하는 부분.'<타 프로토콜 이름>'을 지정하게 되면 해당 프로토콜의 내용을 가져와 현재 프로토콜에 포함한다.
ex)프로토콜을 선언하는 brush 클래스가 구현되는 방식
//Brush.h
#import <Foundation/Foundation.h>
@protocol BrushDelegate; //(1)
@interface Brush : NSObject {
id<BrushDelegate> deleage; //(2)
}
@property (nonatomic, retain) id<BrushDelegate> delegate;
-(void)changeColor; //(3)
@end
@protocol BrushDelegate<NSObject> //(4)
@optional //(5)
-(void)brush(Brush *)brush WillStartChangingColor:(UIColor *)color;
-(void)brush(Brush *)brush didStartChangingColor:(UIColor *)color;
-(void)brush(Brush *)brush willFinishChangingColor:(UIColor *)color;
-(void)brush(Brush *)brush didFinishChangingColor:(UIColor *)color;
@end
//Brush.m
#import "Brush.h"
@implementation Brush
@synthesize delegate;
-(void)ChangeColor { //(6)
UIColor *color = [UIColor blackColor];
if([self.delegate respondsToSelector:@selector(brush:willStartChangingColor;)]) {
[self.delegate brush:self WillStartChangingColor:color];
}
…..
}
@end
respondsToSelector 는 메소드를 호출하는 것에 주목하자. 이 메소드는 NSObject에 선언된 것인데, 호출하고 있는 객체 내에 어떠한 메소드가 정의되어 있는지 검사한다.
2. 프로토콜(BrushDelegate )을 사용하고자 하는 클래스의 구조
//헤더 파일
#import "프로토콜을 선언한 헤더파일" //(1)프로토콜을 선언한 헤더 파일을 추가
…
@interface 클래스이름 : 부모클래스이름 <사용하려고하는 프로토콜이름>{ //(2) 사용하려는 프로토콜이름 명시
프로토콜을 선언하고 있는 클래스 타입 인스턴스 변수 //(3)프로토콜클래스의 인스턴스변수 선언
}
…
@end
//소스파일
#import "헤더 파일"
@implementation
@synthesize (3)에서 선언된 인스턴스 변수
….
인스턴스 변수(3)에게 프로토콜을 사용하고자 하는 현재 클래스 인스턴스의 주소값을 넘겨줌 //(4)
프로토콜 내에 선언된 메소드 정의 //(5)
…
@end
(4)현재 클래스 인스턴스의 주소값을 넘겨줌(5)에서 정의하고 있는 메소드가 정상적으로 호출되도록 한다.
(5) 프로토콜을 선언하여 정의하고 있는 클래스에서는 메소드를 선언만 하고 있을 뿐 구현은 하지 않고 있다. 이는 전적으로 프로토콜을 사용하는 클래스의 몫으로 남겨져 있다. 그러므로 해당 메소드에 대한 구현 부분이 반드시 이곳을 존배해야한다.
ex)BrushDelegate를 사용한 Rectangle 클래스
//Rectangle.h
#import <Foundation/Foundation.h>
#import "Shape.h"
#import "Brush.h"
@class Circle;
@interface Rectangle : shape <BrushDelegate> {
@protected
Brush *brush;
NSString *name;
NSInteget width;
NSInteget height;
}
@property (nonatomic, retain)Brush *brush;
@property (nonatomic, retain)NSString *name;
@property (nonatomic, retain)NSInteger width;
@property (nonatomic, retain)NSInteger height;;
-(id) initWithWidth:(NSInteger)myWidth height:(NSInteger)myHeight;
-(NSString *)description;
-(void)draw;
@end
//Rectangle.m
@import "Rectangle.h"
@implementation Rectangle
@synthesize brush;
@synthesize name;
@synthesize width;
@synthesize height;
-(id)init{
return [self initWithWidth:10 height:20];
}
-(id) initWihWidth:(NSInteger)myWidth height:(NSInteger)myHeight{
if(self =[super init]){
brush =[[Brush alloc] init];
brush.delegate = self;
name = nil;
width = myWidth;
height = myHeight;
}
return self;
}
-(void)brush(Brush *)brush WillStartChangingColor:(UIColor *)color
{…}
-(void)brush(Brush *)brush didStartChangingColor:(UIColor *)color
{…}
-(void)brush(Brush *)brush willFinishChangingColor:(UIColor *)color
{…}
-(void)brush(Brush *)brush didFinishChangingColor:(UIColor *)color
{…}
-(NSString *)description{
NSString *text =nil;
Text = [[NSString alloc] initWithString:@"Test";
[text autorelease];
return text;
}
-(void)draw{
[super draw];
}
-(void)dealloc{
[name release];
[super dealloc];
}
@end
프로토콜 내에는 하나 또는 그 이상의 메소드를 선언할 수 있으며, 이들은 이후 이 프로토콜을 사용하고자 하는 클래스의 소스파일에서 정의한다. 그리고 이 프로토콜을 이용하는 클래스가 있어야한다. 당연한 이야기이겠지만 프로토콜을 이용하는 클래스의 수와 종류에는 제한이 없다. 어느 클래스라도 프로토콜을 선언하고 있는 클래스를 자신의 멤버 변수로 포함하고 이용하면 되는 것이다.
실제로 파운데이션 프레임워크 내의 많은 클래스도 이처럼 프로토콜을 이용할 수 있도록 구현되어 있다.
다양한 프로토콜 메소드를 이용하는 대표적인 예로 테이블뷰(UITableView)를 들수 있다.
8.카테고리와 클래스 확장
카테고리는 특정 클래스의 소스를 가지고 있지 않더라도 해당 클래스에 새로운 메소드를 추가하는 것을 상속 없이 가능케한다.
8-1클래스에 메소드 추가하기
//헤더파일
#import "클래스 이름" //(1)카테고리를 이용해서 메소드를 추가하고자 하는 클래스의 헤더 파일을 추가한다.
@interface 클래스 이름 (카테고리 이름) //(2)클래스 이름 괄호안에 카테고리 이름을 지정
//메소드 선언 //(3)클래스에 추가하는 메소드를 선언 인스턴스변수는 추가할 수 없다.
@end
//소스 파일
#import "헤더 파일" //(4)헤더 파일을 추가한다. 일반적으로 파일의 이름은"클래스이름+카테고리이름'으로 지정
@implementation 클래스 이름 (카테고리 이름)
//메소드 정의 //(5) 클래스에 추가 선언한 메소드를 정의한다.
@end
ex)카테고리 예
//Rectangle+Display.h
#import <Foundation/Foundation.h>
#import "Rectangle.h"
@interface Rectangle (Display)
-(void)displayDetail;
@end
//Rectangle+Display.m
#import "Rectangle+Display.h"
@implementation Rectangle(Display)
-(void)displayDetail{
…
}
@end
8-2 카테고리의 장점과 단점
-장점
*유사한 메소드를 한곳으로 모아 관리할수 있다.
*여러 개발자가 동시에 하나의 큰 클래스를 설계하고 구현할 때 카테고리로 나눠 작업 할 수 있다.
*큰 클래스를 여러 카테고리로 분리해놓으면 컴파일 할 때 전체를 빌드하지 않고 일부만 컴파일 할수 있다.
-단점
*부모 클래스의 메소드를 재정의(오버라이딩)하고 있는 클래스 메소드를 카테고리에서 또다시 재정의하면 문제가 발생한다. 카테고리에서 부모 클래스의 메소드는 super 지시어를 이용하여 접근할 수 있으나, 클래스에서 이전에 재정의한 메소드는 호출할 방법이 없기 때문이다.
*클래스의 메소드는 둘 이상의 카테고리에서 재정의하면 문제가 발생한다. 두 메소드중 어느 것이 우선권을 가지는지 알수 없기때문이다.
*기존 메소드를 재정의 하는 것 이외에도 문제가 생길 수 있다.
8-3.루트 클래스의 카테고리
루트 클래스인 NSObject에 카테고리를 이용하여 메소드를 추가하면 프로젝트의 모든 코드에서 이를 사용할 수 있게 되므로 매우 위험하다. 또한 루트 클래스에는 부모 클래스가 없으므로 루트 클래스에 메소드를 추가할 때 super지시어를 사용해서는 안된다.
그리고 루트 클래스는 다른 클래스와 달리 클래스 객체(인스턴스 변수가 아닌 클래스 이름 자체를 사용하는 경우)에서도 클래스 메소드 뿐 아니라 인스턴스 메소드를 호출할 수 있다는 사실을 기억해두자
8-4.클래스 확장
클래스 확장은 카테고리와 거의 유사하다. 다른 점은 카테고리 이름을 사용하지 않으며, 메소드를 구현하는 부분이 확장하려는 클래스의 구현 부분에 반드시 존재해야한다는 것이다.
ex)
//Rectangle.h
#import <Foundation/Foundation.h>
#import "Shape.h"
#import "Brush.h"
@class Circle;
@interface Rectangle :Shape <BrushDelegate>{
@protected
Brush *brush;
NSString *name;
NSInteger width;
NSInteger height;
}
@property (nonatomic, retain) Brush *brush;
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSInteger width;
@property (nonatomic, retain) NSInteger height;
-(id) initWithWidth:(NSInteger)myWidth height:(NSInteger)myHeight;
-(NSString *)description;
-(void)draw;
@end
@interface Rectangle()
-(void)displayDetailEx;
@end
//Rectangle.m
#import "Rectangle.h"
@implementation Rectangle
@synthesize brush;
@synthesize name;
@synthesize width;
@synthesize height;
…..
-(void)displayDetailEx{
..
}
…
@end
'Objective_C' 카테고리의 다른 글
[Objective-C] 기초배우기 (4) (0) | 2020.04.14 |
---|---|
[Objective-C] 기초배우기 (2) (0) | 2020.04.14 |
[Obejective-C] 기초배우기 (1) (0) | 2020.04.13 |