<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Codethink &#187; cocoa</title>
	<atom:link href="https://codethink.no-ip.org/tags/cocoa/feed" rel="self" type="application/rss+xml" />
	<link>https://codethink.no-ip.org</link>
	<description>A blog about coding, life, and other arbitrary topics</description>
	<lastBuildDate>Sun, 15 Mar 2026 21:30:15 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.29</generator>
	<item>
		<title>[Objective-C + Cocoa] Screen Capture, Multiplexing, and More</title>
		<link>https://codethink.no-ip.org/archives/541</link>
		<comments>https://codethink.no-ip.org/archives/541#comments</comments>
		<pubDate>Mon, 28 Mar 2011 11:45:02 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[objc]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=541</guid>
		<description><![CDATA[It&#8217;s been a bit quiet on the coding-front lately, so I thought I&#8217;d share a small handful of various utilities that I&#8217;ve developed over the past few weeks. None of them are particularly revolutionary, but they can certainly prove useful &#8230; <a href="https://codethink.no-ip.org/archives/541">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>It&#8217;s been a bit quiet on the coding-front lately, so I thought I&#8217;d share a small handful of various utilities that I&#8217;ve developed over the past few weeks.  None of them are particularly revolutionary, but they can certainly prove useful in the right situations.  Anyways, in no particular order, I give you:</p>
<p><strong>ScreenCaptureView</strong></p>
<p>This bit of code allows you to easily capture the contents of any arbitrary UIView:</p>
<pre class="brush: cpp; title: ; notranslate">//  ScreenCaptureView.h
#import &lt;UIKit/UIKit.h&gt;

@interface ScreenCaptureView : UIView {
}

@property(retain) UIImage* currentScreen;
@property(assign) float frameRate;

@end


//  ScreenCaptureView.m
#import &quot;ScreenCaptureView.h&quot;
#import &lt;QuartzCore/QuartzCore.h&gt;

@implementation ScreenCaptureView

@synthesize currentScreen, frameRate;

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.contentMode = UIViewContentModeRedraw;
        self.frameRate = 20.0f;//20 frames per seconds
    }
    return self;
}

- (void) drawRect:(CGRect)rect {
    CGContextRef context =  UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    CGImageRef cgImage = CGBitmapContextCreateImage(context);
    UIImage* background = [UIImage imageWithCGImage: cgImage];
    CGImageRelease(cgImage);
    self.currentScreen = background;
    
    [self performSelector:@selector(setNeedsDisplay) withObject:nil afterDelay:(1.0 / self.frameRate)];   //redraw at the specified framerate
}

- (void)dealloc {
    [super dealloc];
}
@end</pre>
<p>The &#8216;<em>ScreenCaptureView</em>&#8216; class automatically captures its current contents (including any nested subviews) to a UIImage which it exposes through the &#8216;<em>currentScreen</em>&#8216; property.  You can use this functionality to do things like generate screenshots of your application for use in help/tutorial (or promotional) content, and you can even pass the data as frames to an `<em>AVCaptureSession</em>` to create a live video of your app in action.</p>
<p><strong>Update:</strong>  An enhanced version of this class that includes the ability to record video is <a href="http://codethink.no-ip.org/wordpress/archives/673">now available</a>.</p>
<p><strong>MultiplexingDelegate</strong></p>
<p>For those rare cases when you want multiple delegate objects to be notified of a change/event in some object:</p>
<pre class="brush: cpp; title: ; notranslate">//  MultiplexingDelegate.h
#import &lt;Foundation/Foundation.h&gt;

@interface MultiplexingDelegate : NSObject {
    NSMutableArray* delegates;
}

- (void) addDelegate: (id) theDelegate;
- (void) removeDelegate: (id) theDelegate;
- (void) sendSelectorToDelegates: (SEL)selector withObject: (id)param1 andSecondObject: (id)param2
@end

//  MultiplexingDelegate.m
@implementation MultiplexingDelegate
- (id) init {
    if ((self = [super init])) {
        delegates = [[NSMutableArray alloc] initWithCapacity: 16];
    }
}

- (void) dealloc {
    [delegates release];
    [super dealloc]
}

- (void) addDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate &amp;&amp; ! [delegates containsObject: theDelegate]) {
            [delegates addObject: theDelegate];
        }
    }
}

- (void) removeDelegate: (id) theDelegate {
    @synchronized(delegates) {
        if (theDelegate &amp;&amp; [delegates containsObject: theDelegate]) {
            [delegates removeObject: theDelegate];
        }
    }
}

- (void) sendSelectorToDelegates: (SEL)selector withObject: (id)param1 andSecondObject: (id)param2 {
    @synchronized(delegates) {
        for (id theDelegate in delegates) {
            if (param2) {
                [theDelegate performSelector:selector withObject:param1 withObject:param2];
            }
            else if (param1) {
                [theDelegate performSelector:selector withObject:param1];
            }
            else {
                [theDelegate performSelector:selector];
            }
        }
    }
}
@end</pre>
<p>The &#8216;<em>MultiplexingDelegate</em>` class provides a generic starting point for creating delegates that conform to various protocols and support the multiplexing of events to any number of attached listeners.  To use it you just need to create a new subclass of &#8216;<em>MultiplexingDelegate</em>&#8216; that implements whatever protocol you are interested in.  For instance, here is a partial example of a multiplexing UISearchBarDelegate implementation:</p>
<pre class="brush: cpp; title: ; notranslate">//  MultiplexingSearchBarDelegate.h
#import &lt;UIKit/UIKit.h&gt;
#import &quot;MultiplexingDelegate.h&quot;

@interface MultiplexingSearchBarDelegate : MultiplexingDelegate&lt;UISearchBarDelegate&gt; {
}
@end

//  MultiplexingSearchBarDelegate.m
@implementation MultiplexingSearchBarDelegate
//add UISearchBarDelegate methods here, following a pattern like this:
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self sendSelectorToDelegates: @selector(searchBar:textDidChange:) withObject: searchBar andSecondObject: searchText];
}

//or alternately/equivalently, a pattern like this:
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    @synchronized(delegates) {
        for (id&lt;UISearchBarDelegate&gt; theDelegate in delegates) {
            [theDelegate searchBar:searchBar shouldChangeTextInRange: range replacementText: text];
        }
    }
}
@end</pre>
<p>To use the &#8216;<em>MultiplexingSearchBarDelegate</em>&#8216; class you would create a single instance and add it as the delegate of your UISearchBar.  Then you just register every other object that you want to receive UISearchBar events with the &#8216;<em>MultiplexingSearchBarDelegate</em>&#8216; (by using the &#8216;<em>addDelegate:</em>&#8216; method), and they will all receive event notifications from the UISearchBar.  Simple, but powerful.</p>
<p><strong>NSString+JavaAPI</strong></p>
<p>There&#8217;s no getting around it, the standard NSString API just kind of sucks.  Wouldn&#8217;t it be great if NSString supported an API that was more like what Java provides through its String class?  Well now it can:</p>
<pre class="brush: cpp; title: ; notranslate">//  NSString+JavaAPI.h
#import &lt;Foundation/Foundation.h&gt;

@interface NSString (NSString_JavaAPI)
- (int) compareTo: (NSString*) comp;
- (int) compareToIgnoreCase: (NSString*) comp;
- (bool) contains: (NSString*) substring;
- (bool) endsWith: (NSString*) substring;
- (bool) startsWith: (NSString*) substring;
- (int) indexOf: (NSString*) substring;
- (int) indexOf:(NSString *)substring startingFrom: (int) index;
- (int) lastIndexOf: (NSString*) substring;
- (int) lastIndexOf:(NSString *)substring startingFrom: (int) index;
- (NSString*) substringFromIndex:(int)from toIndex: (int) to;
- (NSString*) trim;
- (NSArray*) split: (NSString*) token;
- (NSString*) replace: (NSString*) target withString: (NSString*) replacement;
- (NSArray*) split: (NSString*) token limit: (int) maxResults;
@end

//  NSString+JavaAPI.m
#import &quot;NSString+JavaAPI.h&quot;

@implementation NSString (NSString_JavaAPI)
- (int) compareTo: (NSString*) comp {
    NSComparisonResult result = [self compare:comp];
    if (result == NSOrderedSame) {
        return 0;
    }
    return result == NSOrderedAscending ? -1 : 1;
}

- (int) compareToIgnoreCase: (NSString*) comp {
    return [[self lowercaseString] compareTo:[comp lowercaseString]];
}

- (bool) contains: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location != NSNotFound;
}

- (bool) endsWith: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == [self length] - [substring length];
}

- (bool) startsWith: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == 0;
}

- (int) indexOf: (NSString*) substring {
    NSRange range = [self rangeOfString:substring];
    return range.location == NSNotFound ? -1 : range.location;
}

- (int) indexOf:(NSString *)substring startingFrom: (int) index {
    NSString* test = [self substringFromIndex:index];
    return [test indexOf:substring];
}

- (int) lastIndexOf: (NSString*) substring {
    if (! [self contains:substring]) {
        return -1;
    }
    int matchIndex = 0;
    NSString* test = self;
    while ([test contains:substring]) {
        if (matchIndex &gt; 0) {
            matchIndex += [substring length];
        }
        matchIndex += [test indexOf:substring];
        test = [test substringFromIndex: [test indexOf:substring] + [substring length]];
    }
    
    return matchIndex;
}

- (int) lastIndexOf:(NSString *)substring startingFrom: (int) index {
    NSString* test = [self substringFromIndex:index];
    return [test lastIndexOf:substring];
}

- (NSString*) substringFromIndex:(int)from toIndex: (int) to {
    NSRange range;
    range.location = from;
    range.length = to - from;
    return [self substringWithRange: range];
}

- (NSString*) trim {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

- (NSArray*) split: (NSString*) token {
    return [self split:token limit:0];
}

- (NSArray*) split: (NSString*) token limit: (int) maxResults {
    NSMutableArray* result = [NSMutableArray arrayWithCapacity: 8];
    NSString* buffer = self;
    while ([buffer contains:token]) {
        if (maxResults &gt; 0 &amp;&amp; [result count] == maxResults - 1) {
            break;
        }
        int matchIndex = [buffer indexOf:token];
        NSString* nextPart = [buffer substringFromIndex:0 toIndex:matchIndex];
        buffer = [buffer substringFromIndex:matchIndex + [token length]];
        if (nextPart) {
            [result addObject:nextPart];
        }
    }
    if ([buffer length] &gt; 0) {
        [result addObject:buffer];
    }
    
    return result;
}

- (NSString*) replace: (NSString*) target withString: (NSString*) replacement {
    return [self stringByReplacingOccurrencesOfString:target withString:replacement];
}
@end</pre>
<p>Note that this isn&#8217;t the complete Java String API (and also that `<em>split()</em>` does not support regular-expressions as it does in Java).  It is just a subset consisting of the most useful Java API functions that do not have convenient analogs in the standard NSString API.  Still, it makes a lot of common string manipulations a lot more straightforward than they otherwise would be.</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/541/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>[Objective-C + Cocoa]  The Poor-man&#8217;s Multithreading</title>
		<link>https://codethink.no-ip.org/archives/104</link>
		<comments>https://codethink.no-ip.org/archives/104#comments</comments>
		<pubDate>Fri, 28 Jan 2011 14:50:36 +0000</pubDate>
		<dc:creator><![CDATA[aroth]]></dc:creator>
				<category><![CDATA[coding]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[objc]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://codethink.no-ip.org/wordpress/?p=104</guid>
		<description><![CDATA[I&#8217;ve been doing a fair bit of coding in Objective-C lately, more specifically using Apple&#8217;s Cocoa API. There&#8217;s a lot to like about Objective-C as a language. Predating Java by nearly a decade, here is a reflective language that more &#8230; <a href="https://codethink.no-ip.org/archives/104">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been doing a fair bit of coding in <a href="http://en.wikipedia.org/wiki/Objective-c" target="_blank">Objective-C</a> lately, more specifically using Apple&#8217;s <a href="http://en.wikipedia.org/wiki/Cocoa_(API)" target="_blank">Cocoa API</a>.  There&#8217;s a lot to like about Objective-C as a language.  Predating Java by nearly a decade, here is a reflective language that more closely adheres to that fundamental object-oriented paradigm of message-passing between objects than many more-modern languages do.  This is even more impressive considering that the language is built on top of C, a 38 year old language with no support for objects, reflection, most other concepts introduced by the object-oriented paradigm, or even a convenient syntax for declaring and using data structures.</p>
<p>Conceptually, one can reason out that Objective-C accomplishes many of its neat tricks by using the <em>performv:</em> selector and a few clever lookup tables placed in strategic locations.  For instance, if the member functions for an object are referenced in a function table that is keyed by function name (or more appropriately, selector), and the <em>performv:</em> selector always consults this table when performing a method invocation, then adding new functions to an object can be accomplished, even at runtime, by simply adding some new table entries.  It&#8217;s a pretty elegant design, really, although that&#8217;s a subject for another day, perhaps.</p>
<p>The subject for today is a somewhat simple, somewhat less elegant method that is an integral part of the Cocoa API:</p>
<pre class="brush: cpp; title: ; notranslate">- (void)performSelector:(SEL)sel withObject:(id)arg 
		afterDelay:(NSTimeInterval)secs</pre>
<p>What this method does is schedule a given method invocation on the current run loop, to be executed after some amount of delay, specified in seconds.  As a brief aside, &#8220;run-loops&#8221; are an outdated, non-intuitive, and over-complicated concept, and they should go away.  Viewed abstractly, a run loop is simply an execution context.  It executes a stream of commands serially relative to other commands in the run loop, and in parallel relative to commands being executed in other run loops.  In essence, a run loop is simply a thread.  It provides an execution context that is asynchronous from other execution contexts in the runtime environment, just like a thread does.  And there is little reason to complicate the matter by inventing a new concept to use to model something that every modern Computer Science student is exposed to in their first year of college.</p>
<p>But anyways, the <em>performSelector:</em> method (and its numerous variants) allows a developer to schedule a particular method invocation to occur at some later point in time on the current thread (I shall not be using the term &#8220;run loop&#8221; any longer).  Other instructions on the thread continue to execute as normal between the time <em>performSelector:</em> is called and the time when the target method is invoked (i.e. using this method does not block the current thread).  It&#8217;s almost, but not quite, like scheduling the execution of a function closure, and can be used to create a kind of poor-man&#8217;s multi-threading.  </p>
<p>As noted, the method invocation is actually scheduled to execute on the current thread, so there is no true concurrency occurring here; merely the illusion of concurrency.  But in many cases, the illusion of concurrency is all that&#8217;s really required.  To draw a parallel to other languages, the <em>performSelector:</em> method is comparable to the <em>setTimeout()</em> function that is present in both <a href="http://en.wikipedia.org/wiki/JavaScript" target="_blank">JavaScript</a> and <a href="http://en.wikipedia.org/wiki/Actionscript" target="_blank">ActionScript</a>.  Both of these languages use a single-threaded runtime environment, but can provide the illusion of concurrency through use of the <em>setTimeout()</em> call.  Conceptually, the execution engine that these languages use is simply processing a queue of function closures.  While there is a closure that is scheduled to execute, the engine dequeues and executes it, otherwise it sleeps until there is a new closure scheduled in the queue.  And so it is in a Cocoa thread, except that instead of a queue of function closures, you have a queue of selectors (or &#8220;messages&#8221;, or &#8220;method invocations&#8221;, as you prefer).</p>
<p>There are a number of uses for this not-quite-concurrency, such as monitoring the status of an object or operation and then posting a notification to some delegate when that status changes.  For instance, here is some simple code to detect the end of a UIView <em>startAnimating</em> sequence:</p>
<pre class="brush: cpp; title: ; notranslate">@implementation AnimatingView 
- (void) checkStatus {
	if([self isAnimating]) {
		//animation is still running, check later
		[self performSelector:@selector(checkStatus)
			withObject:nil afterDelay: 0.1];
		return;  //be sure to do this here
	}

	//animation is done, notify and release our delegate
	[animDelegate notifyAnimationComplete];
	[animDelegate release];
}

- (void) runAnimationAndNotify: (id) objToNotify {
	//[set up your animation stuff here]
	
	//retain the object that we want to notify
	animDelegate = [objToNotify retain];
	[self startAnimating];  //start the animation
		
	//schedule a status notification check
	[self performSelector:@selector(checkStatus)
		withObject:nil afterDelay: 0.1];
}
@end</pre>
<p>In many other languages, the above code can only be implemented by spawning a new thread to monitor the status of the animation (or by blocking/sleeping the current thread while the animation is running).  You can do it that way in Objective-C as well, but the above method has a couple of advantages over using a dedicated thread:</p>
<ul>
<li>No thread creation overhead.  Since the current thread is used, no additional resources need to be allocated on spawning a thread just to handle the notification dispatch.</li>
<li>No need to worry about concurrency/synchronization issues.  Because the notification is sent from the same thread that started the animation, there is no need to worry about the notification arriving when the calling object is in the middle of doing something else (unless your program has other threads that are making use of that same object).</li>
</ul>
<p>Of course, there are some caveats associated with this approach, as well:</p>
<ul>
<li>If the current thread blocks or sleeps, the notification will be delayed.  Obviously if you are doing things on your thread that would cause it to block or sleep for a long duration of time, you should not use this approach.</li>
<li>If too much other work is being done on the current thread, then the timing of the notification will be unreliable.  That&#8217;s just the nature of the beast, just like how ActionScript and JavaScript timers lose their accuracy as CPU load approaches 100%.  If your workload is heavy enough to saturate a CPU core, you are better off splitting it up into multiple full-fledged threads.</li>
</ul>
<p>Overall, however, this is a useful technique for those situations where you want concurrent behavior without having to pay the resource and synchronization cost of true concurrency.  It&#8217;s not appropriate in every situation, but if you have a simple task that you&#8217;re thinking about offloading onto a dedicated thread, this approach may be a quicker and simpler alternative.</p>
<p>Finally, a coding post!</p>
]]></content:encoded>
			<wfw:commentRss>https://codethink.no-ip.org/archives/104/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
