Pointer to Pointer in Objective-C - iphone

I'm trying to learn to play with pointers here.
I have a UIImageView. I need to point its image property to another UIImageViews image property, so that whenever I change the second UIImageViews image, the first one gets updated automatically.
Some pointer manipulation here but I can't seem to get my head around it.

That is impossible. They are just pointers. For example aImageView and bImageView. You can set them's image pointer to point to the same UIImage. But change one of them does NOT change the other.
Maybe you can consider to use KVO to do what you want to do. Change one then your method will be called. Then in your method you can change the other.

you can use Key-Value Observing
from Apple Docs
Key-value observing provides a mechanism that allows objects to be notified of changes to specific properties of other objects.
KVO’s primary benefit is that you don’t have to implement your own scheme to send notifications every time a property changes.
[imageView1 addObserver:self
forKeyPath:#"image"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:NULL];
- (void) observeValueForKeyPath:(NSString *)path ofObject:(id) object change:(NSDictionary *) change context:(void *)context
{
// this method is used for all observations, so you need to make sure
// you are responding to the right one.
}

Try to override the setter. Make a subclass of UIImageView, have a property for second UIImageView and write something like
-(void)setImage:(UIImage*)image{
_image = image;
self.secondImageView.image = image;
}
Hope this helps.

Related

How to debug KVO

In my program I use KVO manually to observe changes to values of object properties. I receive an EXC_BAD_ACCESS signal at the following line of code inside a custom setter:
[self willChangeValueForKey:#"mykey"];
The weird thing is that this happens when a factory method calls the custom setter and there should not be any observers around. I do not know how to debug this situation.
Update: The way to list all registered observers is observationInfo. It turned out that there was indeed an object listed that points to an invalid address. However, I have no idea at all how it got there.
Update 2: Apparently, the same object and method callback can be registered several times for a given object - resulting in identical entries in the observed object's observationInfo. When removing the registration only one of these entries is removed. This behavior is a little counter-intuitive (and it certainly is a bug in my program to add multiple entries at all), but this does not explain how spurious observers can mysteriously show up in freshly allocated objects (unless there is some caching/reuse going on that I am unaware of).
Modified question: How can I figure out WHERE and WHEN an object got registered as an observer?
Update 3: Specific sample code.
ContentObj is a class that has a dictionary as a property named mykey. It overrides:
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
BOOL automatic = NO;
if ([theKey isEqualToString:#"mykey"]) {
automatic = NO;
} else {
automatic=[super automaticallyNotifiesObserversForKey:theKey];
}
return automatic;
}
A couple of properties have getters and setters as follows:
- (CGFloat)value {
return [[[self mykey] objectForKey:#"value"] floatValue];
}
- (void)setValue:(CGFloat)aValue {
[self willChangeValueForKey:#"mykey"];
[[self mykey] setObject:[NSNumber numberWithFloat:aValue]
forKey:#"value"];
[self didChangeValueForKey:#"mykey"];
}
The container class has a property contents of class NSMutableArray which holds instances of class ContentObj. It has a couple of methods that manually handle registrations:
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {
BOOL automatic = NO;
if ([theKey isEqualToString:#"contents"]) {
automatic = NO;
} else {
automatic=[super automaticallyNotifiesObserversForKey:theKey];
}
return automatic;
}
- (void)observeContent:(ContentObj *)cObj {
[cObj addObserver:self
forKeyPath:#"mykey"
options:0
context:NULL];
}
- (void)removeObserveContent:(ContentObj *)cObj {
[cObj removeObserver:self
forKeyPath:#"mykey"];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if (([keyPath isEqualToString:#"mykey"]) &&
([object isKindOfClass:[ContentObj class]])) {
[self willChangeValueForKey:#"contents"];
[self didChangeValueForKey:#"contents"];
}
}
There are several methods in the container class that modify contents. They look as follows:
- (void)addContent:(ContentObj *)cObj {
[self willChangeValueForKey:#"contents"];
[self observeDatum:cObj];
[[self contents] addObject:cObj];
[self didChangeValueForKey:#"contents"];
}
And a couple of others that provide similar functionality to the array. They all work by adding/removing themselves as observers. Obviously, anything that results in multiple registrations is a bug and could sit somewhere hidden in these methods.
My question targets strategies on how to debug this kind of situation. Alternatively, please feel free to provide an alternative strategy for implementing this kind of notification/observer pattern.
Update 4: I found the bug using a mixture of breakpoints, NSLogs, code reviews and sweating. I did not use the context in KVO, although this is definitely another useful suggestion. It was indeed a wrong double registration that - for reasons beyond my comprehension - resulted in the observed behavior.
The implementation including [self willChange...]; [self didChange...] works as described (on iOS 5), although it is far from beautiful. The issue is that as NSArray is not KVO-compliant there is no way to talk about changes to its contents. I had also thought about notifications as suggested by Mike Ash, but I decided to go with KVO as this seemed like a more Cocoa-ish mechanism to do the work. This was arguably not the best of decisions ...
Yes, calling -addObserver: twice will result in two registrations. A class Foo and some subclass of Foo, Bar, may both (legitimately) register for the same notification, but with different contexts (always include the context, always check the context in -observeValueForKeyPath and always call super in -observeValueForKeyPath).
This means that an instance of Bar will register twice, and this is correct.
However, you almost certainly don't want to register the same object/keypath/context more than once accidentally, and as #wbyoung says overriding -addObserver:forKeyPath:options:context: should help you make sure this doesn't happen. If nesessary keeping track of observers/keypath/context in an array and making sure they are unique.
Mike Ash has some interesting thoughts and code on his blog about using contexts. He is right about it being broken but in practise KVO is perfectly useable.
That is, when you use it to do something it is meant todo. It used to be that you absolutely could not do something like this..
[self willChangeValueForKey:#"contents"];
[self didChangeValueForKey:#"contents"];
because it's a lie. The value of 'contents' when you call -willChange.. must be a different value from when you call -didChange... The KVO mechanism will call -valueForKey:#"contents" in both -willChangeValueForKey and -didChangeValueForKey to verify the value has changed. This obviously won't work with an array as no matter how you modify the contents you still have the same object. Now i don't know if this is still the case (a web search turned up nothing) but note that -willChangeValueForKey, -didChangeValueForKey are not the correct way to handle manual kvo of a collection. For that Apple provides alternative methods:-
– willChange:valuesAtIndexes:forKey:
– didChange:valuesAtIndexes:forKey:
– willChangeValueForKey:withSetMutation:usingObjects:
– didChangeValueForKey:withSetMutation:usingObjects:
It may not still be true that the value must change, but if it is, your scheme is not going to work.
What i would do is have one notification for modifications to your collection. And a different notification for modification of items in that collection. i.e. at the moment you are trying to trigger notifications for #"contents" when instead you could have #"contents" and #"propertiesOfContents". You would need to observe two keypaths but you can use automatic kvo instead of manually triggering the notifications. (Using automatic kvo will ensure that the correct versions of -willChange.. -didChange.. are called)
For automatic kvo of an array take a look at (no NSArrayController needed) :-
Key-Value-Observing a to-many relationship in Cocoa
Then each time an item is added to the collection, observe the properties you need (as you are doing now) and when they change flip a value for self.propertiesOfContents. (ok as i read that back it doesn't necessarily sound less hacky than your solution but i still believe it may behave better).
In response to your modified question, try overriding addObserver:forKeyPath:options:context: in your custom class and setting a breakpoint on it. Alternatively, you can just set a symbolic breakpoint on -[NSObject addObserver:forKeyPath:options:context:], but that will probably get hit a lot.

Rotation - slowing it down using willAnimateSecondHalfOfRotationFromInterfaceOrientation

people, how do you actually slow down the orientation-rotation when using the "willAnimateSecondHalfOfRotationFromInterfaceOrientation:" method?
I currently have this:
-(void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
duration:(NSTimeInterval)duration {
[self positionViews];
}
And I understand that this "willAnimate2ndHalf..." method gets called automatically when the rotation does indeed happen - well where do I actually get to change its DURATION value?
If you want to change the overall timing of he app's rotation, it can't be done. willAnimateSecondHalfOfRotationFromInterfaceOrientation is meant for adding custom code, like setting custom coordinates, properties, things like that.

Pointer to a Pointer in Objective-C

I have an NSDictionary with some values. Usually, the values in the NSDictionary are static, but in some rare cases (user changes settings), the NSDictionary changes.
The dictionary is used application wide and stored in the app delegate.
The problem that I have now: When the settings change, I release the old dictionary and create a new one. How do I now inform all the relevant parties? I thought of storing NSDictionary** pointers and deference them as I need, in order to get the NSDictionary* (there is never a case where the dictionary is released and not recreated).
NSMutableDictionary* dict = [NSMutableDictionary alloc] init];
...
NSDictionary** ref = &dict;
When I run the debugger I can see that dereferencing ref does get me dict initially. But after some time, it seems that ref is pointing to nirvana. Wondering whether I need to manage memory or sth. for NSDictionary**? Since it's not a pointer to an object, retaining it doesn't make sense. But it does seem like a memory issue?
I'm not going to comment on the complexity of pointers, because that's really not relevant to this situation. Furthermore, I'm not really sure what it is that you want, but I think you are looking for a way to observe changes from one object in another. The nice thing is that Cocoa provides this out of the box.
So, you'll need to have this dictionary as a property to something (your application delegate). Then, use key-value-observing in whichever objects care, to watch that property for changes:
[appDelegate addObserver:self forKeyPath:#"dictPropertyName"];
Then, implement -observeValueForKeyPath:ofObject:change:context::
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:#"dictPropertyName"]) {
// your property has changed; respond to that here
}
}
Let me know if this is something like what you wanted.
Jonathan's answer is correct. However, since this is a global sort of thing, it might make as much or more sense to simply use a notification to let all interested parties know that the dictionary has changed.
Specifically, see NSNotificationCenter and NSNotification.

How do you check to see if a variable has changed every second or less in objective c?

I am using an if statement to check the value of a BOOLEAN when i click on a button. When the button is clicked if the value is false i want to display a UIActivityIndicator and if the value is true i want to push the new view. I can do this fine but i want the view to change automatically when the BOOLEAN Becomes true if the user has already clicked the button.
So my question is how do you check to see if a value has changed everysecond or less?
Look into KVO — Key-Value Observing — to trigger an action when a variable changes its value.
In your view controller's -viewWillAppear: method, for example, add the observer:
[self addObserver:self forKeyPath:#"myBoolean" options:NSKeyValueObservingOptionNew context:nil];
In your -viewWillDisappear: method, unregister the observer:
[self removeObserver:self forKeyPath:#"myBoolean"];
It's important to do this last step, so that the -dealloc method doesn't throw an exception.
Finally, set up the observer method to do something when there is a change to myBoolean:
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqual:#"myBoolean"]) {
// The BOOL value of myBoolean changed, so do something here, like check
// what the new BOOL value is, and then turn the indicator view on or off
}
}
The Key-Value Observing pattern is a good, general way to trigger something when an object's value changes somewhere. Apple has written a good "quick-start" document that introduces this topic.
Have a look a Key-Value Observing (often referred to simply as KVO). It uses the language's dynamic introspective capabilities to implement exactly this functionality for you.
I think you want to look into the Observer Pattern.

I need help with Animation Callbacks (iPhone)

I am creating an application in iPhone and I have several UIViews and layers in it. I am doing some animations using CAKeyframeAnimation class and since the animations have to be chained, I have overridden the animationDidStop method in UIView.
I am getting the callbacks properly, however I just couldn't figure out how I can find which animation was ended so that I can start the next one. Only parameters to the callback function is a CAAnimation object and a boolean.
I can workaround this problem by setting a property in the class and using an enum for the various animations I use. However I just wanted to know if there is any built in attributes in the callbacks which I can set in the CAKeyframeAnimation object and then refer the same in the callback.
Any help would be greatly appreciated!
You can specify a name for an animation and read it in your delegate method.
[animation setValue:"firstAnimation" forKey:#"name"];
...
- (void)animationDidStop:(CAAnimation*)animation finished:(BOOL)finished {
if([[animation valueForKey:#"name"] isEqual:#"firstAnimation"] && finished) {
...
}
}
I know that you said that you're using CAKeyframeAnimations, but if you want simple animation of UIView properties (origin, bounds, alpha, etc.), you can wrap the change of the property or properties in a begin / commit block and specify a delegate method that is called upon completion of the animation. As long as the delegate method takes three arguments, you can call it whatever you want. For example:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:ANIMATIONDURATIONINSECONDS];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:#selector(yourAnimationHasFinished:finished:context:)];
// Change property or properties here
[UIView commitAnimations];
will cause the method
- (void)yourAnimationHasFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context;
to be called. The arbitrary naming this allows would provide you with a means of separating handling for the completion of different animations. I prefer this for simple animations.
For dealing with more complex animations that interact directly with CALayers, the animationDidStop:finished: delegate method does return the animation object that has finished. If you are making one instance that is the delegate for multiple animations, you could create an NSMutableDictionary of animations and NSNumbers for use in a switch statement within the animationDidStop:finished: method. As you create the CAKeyframeAnimation, use setObject:forKey: to assign it to its matching number, then use objectForKey: to find the number that corresponds to that animation in the completion method and feed that into a switch statement.