Haru's 개발 블로그

[Objective-C] 객체 생성 메소드 본문

IOS/Objective-C

[Objective-C] 객체 생성 메소드

Haru_29 2023. 3. 9. 21:27
  • 객체 생성(alloc/init) : [[클래스_이름 alloc] init]
    • alloc: 객체 생성
    • init: 초기화
  • 객체 생성 과정에서 동작해야 하는 코드 -> init 메소드 재정의
  • init 메소드 재정의
    • 부모 클래스를 이용한 초기화
    • 부모 클래스의 초기화 과정 성공시 초기화 코드 동작
    • 생성된 객체 반환(self)

 

ex) 사각형 객체 생성시 가로와 세로 길이 자동 설정

-(id)init{
    self = [super init];
    if(self) {
    // 초기화 코드 작성
    	width = 10;
        height = 10;
    }
    return self;
 }

만약, 초기화 과정에 추가 정보가 필요하면 -> initWith 메소드 생성(헤더에 선언)

-(id)initWithWidth:(int)newWidth height:(int)newHeight {
    self = [super init];
    if(self) {
    	width = newWidth;
        height = newHeight;
    }
    return self;
}

객체 생성 예제

Rectangle *rect = [[Rectangle alloc] initWithWidth:20 height:50];

다양한 객체 초기화 메소드 -> 가장 많은 정보를 이용하는 초기화 메소드 재사용

-(id)init {
    return [self initWithWidth:10 height:10]
}

 

팩토리 메소드

  • 팩토리 메소드: 객체 생성 디자인 패턴
  • 객체를 생성하고 반환하는 코드
  • 클래스 메소드 -> 메소드의 이름은 클래스의 이름으로 시작

ex) 사각형 객체를 생성하는 팩토리 메소드

+(id)retangle{
    Rectangle *obj = [[Rectangle alloc]init];
    return obj;
}
+(id)rectangle:(int)width height:(int)height {
    Rectangle *newObj = [[Rectangle alloc]initWithWidth:width height:height];
    return newObj;
}

팩토리 메소드로 객체 생성

Rectangle *obj1 = [Rectangle rectangle];
Rectangle *obj2 = [Rectangle rectangle:10 height:20];

 

 

 

 

 

 

'IOS > Objective-C' 카테고리의 다른 글

[Objective-C] 메모리 관리  (0) 2023.03.11
[Objective-C] 셀렉터와 프로퍼티  (0) 2023.03.10
[Objective-C] 동적 타입과 바인딩  (0) 2023.03.09
[Objective-C] Class 상속  (0) 2023.03.09
[Objective-C] Class 만들어보기  (0) 2023.02.28
Comments