Pointer to a Pointer in Objective-C - iphone

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.

Related

Pointer to Pointer in Objective-C

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.

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.

How to Transfer Data Via KVO Notifications?

so I am able to successfully have another class of mine be notified via KVO notification when a class instance value changes, but I have no idea of how I would go about transferring data between the two objects. I am aware that it is possible to do such things via the context: parameter, however Apple's documentation fails to indicate how to go about doing that.
I am aware that you place a pointer to an object as the context parameter in the addObserver:forKeyPath:options:context: message, but how does the object that is being observed "see" that object that is pointed to so it can make modifications accordingly?
Thanks!
The context argument is not meant as a data-transfer device, it just helps the observing class to distinguish different observations from each other. I’m not sure if you understand KVO right. KVO is used when you want to know about updates to a certain property. Upon receiving the notification you usually do something with the old/new property value:
- (void) observeValueForKeyPath: (NSString*) keyPath ofObject: (id) sender
change: (NSDictionary*) change context: (void*) context
{
id newValue = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(#"New property value: %#.", newValue);
}
In this use case it does not make much sense to talk about “transferring data” between the two parties. If you want to get some extra data in addition to the property changes, you can easily expose that data as a property on the class being observed. Or forget about KVO and trigger a regular NSNotification with all the required data passed as the user info object:
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
foo, #"foo", bar, #"bar", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"Foo"
object:self userInfo:info];
So I got it working like so...
I have an object (obj A) that needs to observe another object (obj B) and implements the following function: observeValueForKeyPath:ofObject:change:context:
Obj B calls the following in its init function:
[self addObserver:[<some singleton class> sharedManager] forKeyPath:#"someVar" options:(NSKeyValueObservingOptionNew) context:self];
Of course the observer class does not need to be a singleton class, but of course it is very convenient. I passed in the object being observed as the context and that allowed obj A to access all ivars for obj B in the observeValueForKeyPath:ofObject:change:context: function.
As I discovered, different background threads aren't used for KVO notifications, so I am reverting back to using protocols to transfer information as they both work out the same.
This form of data transfer is not recommended, but I wanted to just point out that it is indeed possible.

UIViewController subclass initialization

Say I have a FooController subclass of UIViewController that displays a list of Foos. What's the best practice for dealing with my foo property's lifecycle?
Do I define the #property as being read/write? It's not really -- once it's been set, changing it would potentially result in inconsistent state. Do I create the #property as readonly and write a new designated initializer, initWithFoo:(Foo *) aFoo that calls initWithNibName:bundle:? Now I have to create a new instance every time the controller is popped off the stack, and pushed on with a new foo.
The latter seems to me like the approach to take, but I've never seen anyone do this. So what's standard practice?
Properties are generally the way to go. They give you power of KVC/KVO
You should set the class as an observer of the Foo property (KVO). Then everytime Foo is changed, you get a chance to deal with it. No need to worry about inconsistency.
[self addObserver:self forKeyPath:#"foo" options:0 context:#"fooChanged"];
Then observe the change:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if([keyPath isEqualToString:#"foo"]){
//do your thing
}
}
Now it doesn't matter if foo is set in the initializer or some time later, you can deal with it. You don't want to have your code break by forcing any objects to work with you class in a predetermined order. That is very inflexible and generally bad practice. In this way you can deal with these changes gracefully.
Objective-C is dynamic language. So don't be so strict in encapsulation. This ivar could be reached thought KVC anyways.
So #property (readwrite) is OK.

KVO on the iPhone on 3.0 vs 2.2.1, having an issue

Appears the 3.0 NDA has been lifted, so this should be safe to ask. If this is violating an NDA, please let me know so I can remove the post, post-haste.
I have a very trivial implementation for KVO on an NSOperationQueue. My problem is that when compiling against 2.2.1 SDK, I get different results for the NSOperationQueue in question for a device using 3.0 or one using 2.2.1. I've confirmed this on 1 iPod Touch that has 2.2.1, one that has 3.0, and two sets of iPhones with similar setups.
The code looks like this:
// set observer
[self.myOperationQueue addObserver:self forKeyPath:#"operations" options:NSKeyValueObservingOptionNew context:NULL];
// implementation
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:#"operations"]) {
NSInteger operationCount = [[(NSOperationQueue*)object operations] count];
NSArray *operations = [(NSOperationQueue*)object operations];
}
}
As per the code above, the device running 3.0 will return the correct operationCount and the correct operations. A device running 2.2.1 will always return nil for operations and 0 for operationCount.
Can't seem to pin point why this is the case. All builds are compiled against 2.2.1.
NOTE
As per Matt's response below; 'object' is nil on 2.2.1. It is not nil on 3.0.
The values you're getting sound like the object parameter is literally nil. To find the source of the problem, you may wish to check that object and self.myOperationQueue are the same value -- if they are then your self.myOperationQueue is just in a weird state. If they're not equal, then you can just read from self.myOperationQueue instead of object.
However, you are using the NSKeyValueObservingOptionNew option but you're not reading the value that it gives you. The point of NSKeyValueObservingOptionNew is that it passes the new value in the change dictionary.
i.e.
// Inside the observe method
NSArray *newOperationsArray = [change objectForKey:NSKeyValueChangeNewKey];
If you don't want to extract the new value from the change dictionary, you don't need to pass the NSKeyValueObservingOptionNew value (you can just pass 0).