NSMutableArray initWithCapacity nuances

Matt Gallagher has written a pretty informative article on Cocoa’s collection classes, along with a couple of benchmarks (with & without initWithCapacity:, as well as cross class comparisons) http://cocoawithlove.com/2008/08/nsarray-or-nsset-nsdictionary-or.html His test (source available) for an NSMutableArray of length 1,000,000 took 0.582256sec without capacity and just 0.572139sec with capacity. Test | Time [NSMutableArray array] | 0.582256 … Read more

2D arrays using NSMutableArray

First, you must allocate and initialize your objects before use, something like: NSMutableArray * sections = [[NSMutableArray alloc] initWithCapacity:10]; For the rows, you need one object for each, not a single NSMutableArray * rows; Second, depending on whether you’re using Xcode 4.4+ (which introduced subscripting, a.k.a section[i] & section[i] = …) you may have to … Read more

Rebuild an NSArray by grouping objects that have matching id numbers?

NSArray *array = @[@{@”groupId” : @”1″, @”name” : @”matt”}, @{@”groupId” : @”2″, @”name” : @”john”}, @{@”groupId” : @”3″, @”name” : @”steve”}, @{@”groupId” : @”4″, @”name” : @”alice”}, @{@”groupId” : @”1″, @”name” : @”bill”}, @{@”groupId” : @”2″, @”name” : @”bob”}, @{@”groupId” : @”3″, @”name” : @”jack”}, @{@”groupId” : @”4″, @”name” : @”dan”}, @{@”groupId” : @”1″, @”name” … Read more

Finding Intersection of NSMutableArrays

Use NSMutableSet: NSMutableSet *intersection = [NSMutableSet setWithArray:array1]; [intersection intersectSet:[NSSet setWithArray:array2]]; [intersection intersectSet:[NSSet setWithArray:array3]]; NSArray *array4 = [intersection allObjects]; The only issue with this is that you lose ordering of elements, but I think (in this case) that that’s OK. As has been pointed out in the comments (thanks, Q80!), iOS 5 and OS X 10.7 … Read more

Dictionary in Swift with Mutable Array as value is performing very slow? How to optimize or construct properly?

Copy on write is a tricky thing, and you need to think carefully about how many things are sharing a structure that you’re trying to modify. The culprit is here. countToColorMap[colorCount]?.append(CountedColor(color: color as! UIColor, colorCount: colorCount)) This is generating a temporary value that is modified and put back into the dictionary. Since two “things” are … Read more

How do copy and mutableCopy apply to NSArray and NSMutableArray?

copy and mutableCopy are defined in different protocols (NSCopying and NSMutableCopying, respectively), and NSArray conforms to both. mutableCopy is defined for NSArray (not just NSMutableArray) and allows you to make a mutable copy of an originally immutable array: // create an immutable array NSArray *arr = [NSArray arrayWithObjects: @”one”, @”two”, @”three”, nil ]; // create … Read more