16
Chapter 5 Bit Academy 송진석 2011년 9월 4일 일요일

아이폰강의(3)

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: 아이폰강의(3)

Chapter 5

Bit Academy 송진석

2011년 9월 4일 일요일

Page 2: 아이폰강의(3)

NSNotificationCenter & NSNotification

NotificationCenterobject A

object B

object C

object D

post:@”CandleDidChanged”

addObserver: selfname:@”CandleDidChanged”

perform:@selector(uiUpdate:)

addObserver: selfname:@”CandleDidChanged”

perform:@selector(candleUpdate:)

CandleDidChanged를 노티피케이션으로 등록

CandleDidChanged가 발생하면 자신에게 알려달라고 등록등록된 노티가 발생하면 uiUpdate 메소드를 수행

CandleDidChanged가 발생하면 자신에게 알려달라고 등록등록된 노티가 발생하면 candleUpdate 메소드를 수행

2011년 9월 4일 일요일

Page 3: 아이폰강의(3)

NSNotificationCenter ClassInherits fromNSObjectConforms toNSObject (NSObject)Framework/System/Library/Frameworks/Foundation.frameworkAvailabilityAvailable in iOS 2.0 and later.Companion guideNotification Programming TopicsDeclared inNSNotification.h

A notification center maintains a notification dispatch table which specifies a notification set for a particular observer. A notification set is a subset of the notifications posted to the notification center. Each table entry contains three items:• Notification observer: Required. The object to be notified when

qualifying notifications are posted to the notification center.• Notification name: Optional. Specifying a name reduces the set of

notifications the entry specifies to those that have this name.• Notification sender: Optional. Specifying a sender reduces the set of

notifications the entry specifies to those sent by this object.2011년 9월 4일 일요일

Page 4: 아이폰강의(3)

Class Method

+ (id)defaultCenterReturn ValueThe current process’s default notification center, which is used for system notifications.

2011년 9월 4일 일요일

Page 5: 아이폰강의(3)

Instance Method- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSenderParametersnotificationObserverObject registering as an observer. This value must not be nil.notificationSelectorSelector that specifies the message the receiver sends notificationObserver to notify it of the notification posting. The method specified by notificationSelector must have one and only one argument (an instance of NSNotification).notificationNameThe name of the notification for which to register the observer; that is, only notifications with this name are delivered to the observer.If you pass nil, the notification center doesn’t use a notification’s name to decide whether to deliver it to the observer.notificationSenderThe object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

- (void)postNotification:(NSNotification *)notificationPosts a given notification to the receiver.

ParametersnotificationThe notification to post. This value must not be nil.DiscussionYou can create a notification with the NSNotification class method notificationWithName:object: or notificationWithName:object:userInfo:. An exception is raised if notification is nil.

- (void)postNotificationName:(NSString *)notificationName object:(id)notificationSender userInfo:(NSDictionary *)userInfo

Creates a notification with a given name, sender, and information and posts it to the receiver.

ParametersnotificationNameThe name of the notification.notificationSenderThe object posting the notification.userInfoInformation about the the notification. May be nil.

2011년 9월 4일 일요일

Page 6: 아이폰강의(3)

Notification ClassInherits fromNSObjectConforms toNSCodingNSCopyingNSObject (NSObject)Framework/System/Library/Frameworks/Foundation.frameworkAvailabilityAvailable in iOS 2.0 and later.

Notification Class : NotificationCeneter를 통해 전달될 노티피케이션 객체를 정의함

2011년 9월 4일 일요일

Page 7: 아이폰강의(3)

NSNotification Class Method

+ (id)notificationWithName:(NSString *)aName object:(id)anObject Returns a new notification object with a specified name and object.

ParametersaName : The name for the new notification. May not be nil. anObject : The object for the new notification.

+ (id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfoReturns a notification object with a specified name, object, and user information.

ParametersaName : The name for the new notification. May not be nil.anObject : The object for the new notification.userInfo : The user information dictionary for the new notification. May be nil.

2011년 9월 4일 일요일

Page 8: 아이폰강의(3)

NSNotification Instance Method

- (NSString *)name

The name of the notification. Typically you use this method to find out what kind of notification you are dealing with when you receive a notification.- (id)object(sender object)

The object associated with the notification. This is often the object that posted this notification. It may be nil.Typically you use this method to find out what object a notification applies to when you receive a notification.

- (NSDictionary *)userInfo

Returns the user information dictionary associated with the receiver. May be nil. The user information dictionary stores any additional objects that objects receiving the notification mightuse.

2011년 9월 4일 일요일

Page 9: 아이폰강의(3)

통지센터에 관찰자 등록[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uiUpdate:) name:@"CandleDidChanged" object:nil];

default center 객체를 리턴한다

Observer 등록 : LightTheCandleAppDelegate 객체

LightTheCandleAppDelegate 객체의 메소드등록된 노티가 발생하면 실행될 메소드

observer가 관심있는 노티피케이션 이름

LightTheCandleAppDelegate.m 화일의 applicationDidFinishLaunching 메소드에 첨가

2011년 9월 4일 일요일

Page 10: 아이폰강의(3)

통지처리메소드 구현- (IBAction)toggleCandle:(id)sender{! UISwitch *mySwitch = (UISwitch *)sender;! //[myCandle setCandleState:mySwitch.on];! myCandle.candleState = [mySwitch isOn];} - (void)uiUpdate:(NSNotification *)notification{! if ([myCandle candleState]){! ! //ON! ! [candleImageView setImage:myCandle.candleOnImage];! } else {! ! //OFF! ! [candleImageView setImage:myCandle.candleOffImage];! }}@end

setCandleState를 호출해서 postNotification을 실행

2011년 9월 4일 일요일

Page 11: 아이폰강의(3)

통지센터에 포스팅노티피케이션을 올리는 부분은 Candle클래스에서 candleState가 변하는 시점Candle 클래스의 메소드 화일에 있는 candleState setter화일에 notification을 포스팅하는 코드를 첨가한다.

- (void)setCandleState:(BOOL)newState{! candleState = newState;! [[NSNotificationCenter defaultCenter] ! postNotificationName:@"CandleDidChanged" object:nil];}

NSNotification center

candleobject

LightTheCandleAppDelegate object

- (void)uiUpdate:(NSNotification *)notification{! if ([myCandle candleState]){! ! //ON! ! [candleImageView setImage:myCandle.candleOnImage];! } else {! ! //OFF! ! [candleImageView setImage:myCandle.candleOffImage];! }}

candleState의 세터

2011년 9월 4일 일요일

Page 12: 아이폰강의(3)

Key Value Coding- applications to access the properties of an object indirectly by name (or key), rather than directly through invocation of an accessor method or as instance variables.- Key-value coding is a key technology when working with key-value observing- NSObject에서 제공하는 기능 NSObject를 수퍼클래스로 갖는 모든 클래스 객체에 적용 가능- NSDictionary의 내용을 읽고 쓰는 법이 같음

BOOL candleStateValue = [myCandle candleState];[myCandle setCandleState:!candleStateValue];

엑세서 메소드사용

BOOL candleStateValue = myCandle.candleState;myCandle.candleState = !candleStateValue;

property 사용

BOOL candleStateValue = [myCandle valueForKey: @”candleState”];[myCandle setValue : !candleStateValue forKey: @”candleState”];

KVC사용

KVC를 사용할 경우 Candle 클래스는 getter & setter를 구현하지 않아도 된다

2011년 9월 4일 일요일

Page 13: 아이폰강의(3)

Key Value Observing- 오브젝트의 특정 객체변수의 변화를 자동으로 알려주는 기능- NSObject 클래스의 NSKeyValueObserving 프로토콜로 KVO가 구현되어 있으므로 NSObject의 서브클래스의 모든 오브젝트에서 사용이 가능

observer 등록방법[myCandle addObserver:self forKeyPath:@”candleState” options:NSKeyValueObservingOptionNew|NSKeyValueObservingOld context: nil];

관찰하고자하는 객체변수를 가진 객체

관찰변수에 변화시통보를 받을 객체

관찰하고자하는 객체변수

옵저빙 옵션은 변경사항이 통보될 때 어떤 부가정보를 가지길 원하는 지를 설정- NSKeyValueObservingOptionNew : 감시하는 값의 변경된 새값이 부가정보로 넘어옴- NSKeyValueObservingOptionOld : 감시하는 값의 예전 값이 부가정보로 넘어옴- NSKeyValueObservingOptionInitial : 즉시 오브젝트값의 변화를 감시하기 시작한다.addObserver:forKeyPath:options:context:를 호출한 메소드가 끝나기 전에 감시를 시작한다- NSKeyValueObservingOptionPrior : 보통 KVO가 변경 이후 한 번의 통지를 보내는 반면 이 옵션이 설정되면 변경 전후로 통지를 보낸다.

2011년 9월 4일 일요일

Page 14: 아이폰강의(3)

Observing Method관찰자 오브젝트로 등록된 객체에 구현한다.addObserver:에 등록된 객체내에 다음 메소드를 구현한다.

- (void) observerValueForKeyPath:(NSString *)keyPath ofObject: (id)object change:(NSDictionary*)change context:(void)context{

if([keyPath isEqualToString:@”candleState”]){

// do something}

}

2011년 9월 4일 일요일

Page 15: 아이폰강의(3)

프로그램 구현

LightTheCandleAppDelegate.m 화일-applicationDidFinishLaunching 메소드KVC첨가[myCandle setValue: candleOffImage forKey: @candleOffImage”];[myCandle setValue: candleOnImage forKey: @candleOnImage”];[myCandle setValue: [NSNumber numberWithBool:NO] forKey: @candleState”];

KVO첨가[myCandle addObserver:self forKeyPath: @”candleState” options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context : nil];

-dealloc메소드[myCandle removeObserver: self forKeyPath:@”candleState”];

2011년 9월 4일 일요일

Page 16: 아이폰강의(3)

프로그램 구현- (IBAction)toggleCandle:(id)sender{! if ([sender isKindOfClass:[UISwitch class]]){! ! BOOL newState = [sender isOn];! ! [myCandle setValue:[NSNumber numberWithBool:newState] forKey:@"candleState"];! }} - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{! if ([keyPath isEqualToString:@"candleState"]){! ! BOOL newState = [[change valueForKey:NSKeyValueChangeNewKey] boolValue];! ! if (newState){! ! ! //On! ! ! [candleImageView setImage:[object valueForKey:@"candleOnImage"]];! ! ! onOffSwitch.on = YES;! ! ! candleStateLabel.text = @"Candle is now on";! ! } else {! ! ! //Off! ! ! [candleImageView setImage:[object valueForKey:@"candleOffImage"]];! ! ! onOffSwitch.on = NO;! ! ! candleStateLabel.text = @"Candle is Off. please light on";! ! }! }}

2011년 9월 4일 일요일