Показ дописів із міткою blocks. Показати всі дописи
Показ дописів із міткою blocks. Показати всі дописи

четвер, 14 квітня 2011 р.

Sorting NSArray with blocks

iOS4 blocks introduced a new way to sort NSArray. There is no need to provide selectors or functions as comparators any more. All you need is to provide a comparator block which returns one of 3 NSComparator values and take to objects as an argument. The input and output is same as for the outdated selector/function way (you can hardly change general comparator interface) but now your comparator block captures you function context! Additionally all the code is in the same place.

Below is a bit of my recent work code that changes the order of sorting based on the class instance variable m_seatQuality value:

featuresArray = [[unsortedFeaturesArray sortedArrayUsingComparator: ^(id a, id b) {

DMSeatFeature *first = ( DMSeatFeature* ) a;

DMSeatFeature *second = ( DMSeatFeature* ) b;

if ( first.quality == second.quality )

return NSOrderedSame;

else

{

if ( eSeatQualityGreen == m_seatQuality

|| eSeatQualityYellowGreen == m_seatQuality

|| eSeatQualityDefault == m_seatQuality )

{

if ( first.quality < second.quality )

return NSOrderedAscending;

else

return NSOrderedDescending;

}

else // eSeatQualityRed || eSeatQualityYellow

{

if ( first.quality > second.quality )

return NSOrderedAscending;

else

return NSOrderedDescending;

}

}

}] retain];

пʼятниця, 25 березня 2011 р.

iOS blocks aka closures

iOS 4 blocks (Apple's closures) are awesome! Much more power for callback code and asynchronous execution. Though blocks require a bit more attention to memory management then function calls due to capturing calling method variables.

On the other hand, my tests with calling UIKit code adding 322 labels of 2 latin alphabet length each to the view controller yielded 3.5 seconds of execution on the main thread. Compare this with about 10 seconds of execution through dispatch_async call on the global queue with HIGH priority having nothing else added to this queue (iPhone 4 device). At his point more information required to compare blocks performance to exclusive thread execution. Or does it have something to do with non-thread-safety of UIKit?