I want to perform [document doSomething]
as soon as [document isBusy]
is false. What is the best way to do it? I tried it with a while-loop but that delays the following code, which is not what I want.
If isBusy
has a associated setter method, you can call doSomething
in that setter. A better option would be to use Key Value Observing to observe the value of isBusy
and take action when it changes.
If the action a semantic of your document model
From your question both isBusy
and doSomething
are features of your document and the action to doSomething
when isBusy
goes false is appears to be a semantic of your document model and should therefore be implemented by your document model , ie something like:
- (void) setIsBusy:(BOOL)flag
{
if(flag != _isBusy) // check if this is a change
{
_isBusy = flag;
if(flag)
{
// doSomething, or schedule doSomething if it is a long operation etc., e.g.
[self doSomething];
}
}
}
Using KVO to implement semantics within a single object is probably unusual, but there are cases where it is useful. In this case it would replace a direct action with an indirect one - KVO would execute doSomething
at exactly the same point as the above sample code, there would just be a number of intermediate system methods between setIsBusy
and doSomething
plus the associated overhead of setting up the KVO.
If the action is a semantic of your document's client
Of course, if the linkage between these two is independent of your document model, ie is a semantic of the client of your document, then KVO is appropriate and would be implemented in your client . Your client would register as an observer of your document, ie something like:
[document addObserver:self
forKeyPath:@"isBusy"
options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
context:NULL];
in a method of the client. Then in your client when a notification of the change is received take the appropriate action:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqual:@"isBusy"] && object == document)
[document doSomething;
else
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
Use KVC/KVO (Key Value Coding and Key Value Observation). The subject is covered well in the Apple Documentation. KVO and KVC is a basic programming technique which provides may solutions to your problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.