Non-retaining array for delegates

I found this bit of code awhile ago (can’t remember who to attribute it to). It’s quite ingenius, using a Category to allow the creation of a mutable array that does no retain/release by backing it with a CFArray with proper callbacks. @implementation NSMutableArray (WeakReferences) + (id)mutableArrayUsingWeakReferences { return [self mutableArrayUsingWeakReferencesWithCapacity:0]; } + (id)mutableArrayUsingWeakReferencesWithCapacity:(NSUInteger)capacity { … Read more

How do I remove leading & trailing whitespace of NSString inside an NSArray?

The NSArray and the contained NSString objects are all immutable. There’s no way to change the objects you have. Instead you have to create new strings and put them in a new array: NSMutableArray *trimmedStrings = [NSMutableArray array]; for (NSString *string in arrayRefineSubjectCode) { NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; [trimmedStrings addObject:trimmedString]; } arrayRefineSubjectCode = … Read more

Convert NSArray to NSDictionary

Try this magic: NSDictionary *dict = [NSDictionary dictionaryWithObjects:records forKeys:[records valueForKey:@”intField”]]; FYI this is possible because of this built-in feature: @interface NSArray(NSKeyValueCoding) /* Return an array containing the results of invoking -valueForKey: on each of the receiver’s elements. The returned array will contain NSNull elements for each instance of -valueForKey: returning nil. */ – (id)valueForKey:(NSString *)key;

NSArray + remove item from array

NSArray is not mutable, that is, you cannot modify it. You should take a look at NSMutableArray. Check out the “Removing Objects” section, you’ll find there many functions that allow you to remove items: [anArray removeObjectAtIndex: index]; [anArray removeObject: item]; [anArray removeLastObject];

Finding smallest and biggest value in NSArray of NSNumbers

If execution speed (not programming speed) is important, then an explicit loop is the fastest. I made the following tests with an array of 1000000 random numbers: Version 1: sort the array: NSArray *sorted1 = [numbers sortedArrayUsingSelector:@selector(compare:)]; // 1.585 seconds Version 2: Key-value coding, using “doubleValue”: NSNumber *max=[numbers valueForKeyPath:@”@max.doubleValue”]; NSNumber *min=[numbers valueForKeyPath:@”@min.doubleValue”]; // 0.778 seconds … Read more

Static NSArray of strings – how/where to initialize in a View Controller

Write a class method that returns the array. + (NSArray *)titles { static NSArray *_titles; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _titles = @[@”Your Move”, @”Their Move”, @”Won Games”, @”Lost Games”, @”Options”]; }); return _titles; } Then you can access it wherever needed like so: NSArray *titles = [[self class] titles];