🍎 iOS/iOS Application

[iOS] respondsToSelector, μ˜΅μ…”λ„ 체이닝 μ‚¬μš©ν•˜μ—¬ 델리게이트의 선택적 λ©”μ†Œλ“œ(optional method) κ΅¬ν˜„ μ—¬λΆ€ ν™•μΈν•˜κΈ° (in Swift, Objective-C)

TechYeon 2021. 8. 5. 19:24
델리게이트의 선택적 λ©”μ†Œλ“œ(optional method) κ΅¬ν˜„ μ—¬λΆ€ ν™•μΈν•΄λ³΄μž

 

 

Swift와 Objc의 ν”„λ‘œν† μ½œμ—μ„œ λ©”μ†Œλ“œλŠ” ν•„μˆ˜, 선택적 λ©”μ†Œλ“œλ‘œ κ΅¬ν˜„ κ°€λŠ₯ν•˜λ‹€.

선택적 λ©”μ†Œλ“œ(optional method)λ₯Ό ν˜ΈμΆœν•˜κΈ° μ „,

λΈλ¦¬κ²Œμ΄νŠΈκ°€ ν˜ΈμΆœν•˜λŠ” μ„ νƒμžμ— 응닡할 수 μžˆλŠ”μ§€ ν™•μΈν•˜κΈ° μœ„ν•΄ 내성을 μ‚¬μš©ν•΄μ•Ό ν•œλ‹€.!!! 

κ΅¬ν˜„ν•˜μ§€ μ•Šμ€ λ©”μ†Œλ“œ 호좜 μ‹œ null값을 보내 Crashκ°€ λ‚˜κΈ° λ•Œλ¬Έ!!! 😭

λ”°λΌμ„œ, λ°˜λ“œμ‹œ ν”„λ‘œν† μ½œμ˜ μ˜΅μ…”λ„ λ©”μ†Œλ“œ μ‚¬μš© μ „ κ΅¬ν˜„ μ—¬λΆ€λ₯Ό ν™•μΈν•˜λŠ” 절차λ₯Ό μˆ˜ν–‰ν•΄μ•Όν•œλ‹€. πŸ‘πŸ»

 

 


β–Ά Objective-C ν”„λ‘œν† μ½œ λ©”μ†Œλ“œ κ΅¬ν˜„ μ—¬λΆ€ ν™•μΈν•˜κΈ°

 

일단 ObjC μ—μ„œ ν”„λ‘œν† μ½œμ€ μ•„λž˜ μ½”λ“œμ™€ 같이 

ν‚€μ›Œλ“œκ°€ μ—†λŠ” λ©”μ†Œλ“œλŠ” λͺ¨λ‘ ν•„μˆ˜μ μœΌλ‘œ κ΅¬ν˜„ν•΄μ•Ό ν•˜λŠ” λ©”μ†Œλ“œ,

@optional ν‚€μ›Œλ“œ λ‹€μŒμ— λ‚˜μ˜€λŠ” λ©”μ†Œλ“œλ“€μ€ λͺ¨λ‘ μ„ νƒμ μœΌλ‘œ κ΅¬ν˜„ν•˜λ©΄ λ˜λŠ” λ©”μ†Œλ“œ,

@optional ν‚€μ›Œλ“œλ‘œ μ„ μ–Έν•œ λ©”μ†Œλ“œλ“€ 뒀에 λ‹€μ‹œ ν•„μˆ˜ λ©”μ†Œλ“œλ₯Ό μΆ”κ°€λ‘œ μ„ μ–Έν•˜λ €λ©΄ @required ν‚€μ›Œλ“œλ₯Ό λ‹€μ‹œ μ¨μ€λ‹ˆλ‹€.

@protocol MyProtocol : NSObject
-(void)requiredMethod; 
@optional 
-(void)anOptionalMethod; 
@required 
-(void)anotherRequiredMethod; 
@end;

 

그럼 λ‹€μŒκ³Ό 같이 @optional 둜 μ •μ˜λœ λ©”μ†Œλ“œλ₯Ό ν˜ΈμΆœν•΄λ΄…μ‹œλ‹€.

@protocol BViewControllerDelegate <NSObject>
@optional
-(void)sendMessage:(NSString*)message;
@end

 

그리고 λΈλ¦¬κ²Œμ΄νŠΈκ°€ νŠΉμ • λ©”μ†Œλ“œλ₯Ό κ΅¬ν˜„ν–ˆλŠ”μ§€ ν™•μΈν•΄μ€λ‹ˆλ‹€.

Objective-Cμ—μ„œλŠ” respondsToSelector: λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬ ν•΄λ‹Ή 객체의 λ©”μ†Œλ“œ κ΅¬ν˜„ μ—¬λΆ€λ₯Ό 확인 κ°€λŠ₯ν•©λ‹ˆλ‹€.

respondsToSelector:
- (BOOL)respondsToSelector:(SEL)aSelector;

 

respondsToSelector λ©”μ†Œλ“œ νŒŒλΌλ―Έν„°μ— @selector(확인할 λ©”μ†Œλ“œ) λ₯Ό λ„£μ–΄μ€λ‹ˆλ‹€!

λ©”μ†Œλ“œ κ΅¬ν˜„λœ 경우 YESκ°€ 좜λ ₯, μ—†μœΌλ©΄ nil값을 λ³΄λƒ…λ‹ˆλ‹€.

if (self.delegate && [self.delegate respondsToSelector:@selector(sendMessage:)]) {
	[self.delegate sendMessage: _messageField.text];
}

 


β–Ά Swift ν”„λ‘œν† μ½œ λ©”μ†Œλ“œ κ΅¬ν˜„ μ—¬λΆ€ ν™•μΈν•˜κΈ°

 

μ•„λž˜μ™€ 같이 Swiftμ—μ„œ 선택적 λ©”μ†Œλ“œκ°€ μ •μ˜λ˜λ©΄,

λ©”μ†Œλ“œλ‚˜ ν”„λ‘œνΌν‹°λ₯Ό μ‚¬μš©ν•˜λ©΄ ν•΄λ‹Ή νƒ€μž…μ΄ μžλ™μœΌλ‘œ μ˜΅μ…”λ„μ΄ λ©λ‹ˆλ‹€.

예λ₯Όλ“€μ–΄, (Int)->Stringνƒ€μž…μ˜ λ©”μ†Œλ“œλŠ” ((Int)->String)?이 λ©λ‹ˆλ‹€.

전체 ν•¨μˆ˜ νƒ€μž…μ€ νƒ€μž…μ˜ λ©”μ†Œλ“œμ˜ 리턴값이 μ•„λ‹Œ μ˜΅μ…”λ„λ‘œ λž˜ν•‘λ˜κ²Œ λ©λ‹ˆλ‹€.

@objc protocol BViewControllerDelegate {
    @objc optional func sendMessage(message: String)
}

 

λ”°λΌμ„œ, Swiftμ—μ„œλŠ” respondsToSelector:와 같은 νŽΈλ¦¬ν•œ 메타 ν”„λ‘œκ·Έλž˜λ° 도ꡬ가 μ§€μ›λ˜μ§€ μ•Šμ§€λ§Œ,

선택적 λ©”μ†Œλ“œλ₯Ό optional chaining을 μ‚¬μš©ν•˜μ—¬ ν˜ΈμΆœν•©λ‹ˆλ‹€. πŸ‘πŸ»

if((self.delegate) != nil){
  if let method = self.delegate?.sendMessage?(message: messageField.text!){
      method
  }
}

 

728x90
λ°˜μ‘ν˜•