Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 575
Agnius Vasiliauskas Avatar asked Jul 01 '26 11:07

Agnius Vasiliauskas


1 Answers

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.

like image 173
Abhi Beckert Avatar answered Jul 03 '26 05:07

Abhi Beckert