3

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 ? Maybe someone has different solution ? Any ideas ?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Agnius Vasiliauskas
  • 10,935
  • 5
  • 50
  • 70

2 Answers2

6

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.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
3

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

Community
  • 1
  • 1
Greg Sexton
  • 9,189
  • 7
  • 31
  • 37
  • 5
    This will not tell you if an object is mutated while in the array, though. You'd need to observe every single element in the array. – Chuck Sep 17 '10 at 18:43