I have an NSMutableArray which I initialized like this:
- (id)init
{
self = [super init];
if (self) {
playlist = [[NSMutableArray alloc] init];
}
return self;
}
and am populating a table with it. I have a method to count the number of items in the array:
- (NSUInteger)trackCount
{
tracks = [playlist count];
NSLog(@"Number of tracks = %lx", tracks);
return tracks;
}
and I have a label bound to my appDelegate with the model key path trackCount
, but the label doesn't update when tracks are added(nor does the log). What am I doing wrong??
Would it make more sense and/or be easier to get a count of the rows in the table since they should always be the same number?
Thanks
Have you correctly registered playlist
as a dependent key
You need to specify that changes to the playlist object means that trackCount
will change.
This is all part of KVO compliance.
Example
Taken more or less exactly from the link to the documentation I've given you.
Add this to your implementation file:
+ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key {
NSSet *keyPaths = [super keyPathsForValuesAffectingValueForKey:key];
if ([key isEqualToString:@"trackCount"]) {
NSArray *affectingKeys = @[@"playlist"];
keyPaths = [keyPaths setByAddingObjectsFromArray:affectingKeys];
}
return keyPaths;
}
keyPathsForValuesAffectingValueForKey:
is part of the NSKeyValueObservingProtocol
.
What this snippet does is it says that any changes to playlist will trigger a change in trackCount. So any observers of trackCount will be notified of a possible change to trackcount when playlist changes.