Detect changes in NSArray in ObjC
I need to detect change in NSArray object - that is if some object was added/removed to/from NSArray or was just edited in-place. Are there some integrated NSArray hash functions for this task - or I need to write my own hashing function for NSArray ? Ma开发者_开发百科ybe someone has different solution ? Any ideas ?
All objects have a -hash
method but not all objects have a good implementation.
NSArray's documentation doesn't define it's result, but testing reveals it returns the length of the array - not very useful:
NSLog(@"%lu", @[@"foo"].hash); // output: 1
NSLog(@"%lu", @[@"foo", @"bar"].hash); // output: 2
NSLog(@"%lu", @[@"hello", @"world"].hash); // output: 2
If performance isn't critical, and if the array contains <NSCoding>
objects then you can simply serialise the array to NSData
which has a good -hash
implementation:
[NSArchiver archivedDataWithRootObject:@[@"foo"]].hash // 194519622
[NSArchiver archivedDataWithRootObject:@[@"foo", @"bar"]].hash // 123459814
[NSArchiver archivedDataWithRootObject:@[@"hello", @"world"]].hash // 215474591
For better performance there should be an answer somewhere explaining how to write your own -hash
method. Basically call -hash
on every object in the array (assuming the array contains objects that can be hashed reliably) and combine each together mixed in with some simple randomising math.
You could use an NSArrayController
, which is Key-Value-Observing compliant. Unfortunately NSArray
is only KVC compliant. This way you can easily monitor the array controller's arrangedObjects
property. This should solve your problem.
Also, see this question: Key-Value-Observing a to-many relationship in Cocoa
精彩评论