<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>Cool and crazy things you can do with Objective-C and the Cocoa/Cocoa Touch frameworks.</description><title>Fun with Objective-C</title><generator>Tumblr (3.0; @funwithobjc)</generator><link>http://funwithobjc.tumblr.com/</link><item><title>Getting the IMP of the current method</title><description>&lt;p&gt;Once in a very great while, you come across a weird situation where you want to know the &lt;code&gt;IMP&lt;/code&gt; of the current method.  I&amp;#8217;ll just say right now that if you think you need this, you probably don&amp;#8217;t.  That&amp;#8217;s how rare this situation is.&lt;/p&gt;

&lt;p&gt;Regardless, it&amp;#8217;s an interesting question.  How do you get the function pointer for the currently-executing method?&lt;/p&gt;

&lt;p&gt;A few years ago, &lt;a href="http://cocoawithlove.com/2008/02/imp-of-current-method.html"&gt;Matt Gallagher came up with a clever solution&lt;/a&gt; to this using a compiler function called &lt;code&gt;__builtin_return_address()&lt;/code&gt;.  His code still works great with the LLVM 3.0 compiler.  My only beef with it is that there&amp;#8217;s a lot of looping going on.  He&amp;#8217;s looping over the entire superchain, over every single method, looking at the &lt;code&gt;IMP&lt;/code&gt;&amp;#8217;s address and comparing them to another pointer.&lt;/p&gt;

&lt;h2&gt;Pretty Pretty&lt;/h2&gt;

&lt;p&gt;This morning I was thinking about a question on &lt;a href="http://stackoverflow.com"&gt;Stack Overflow&lt;/a&gt; and thought of another way to get the current &lt;code&gt;IMP&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static inline IMP __CurrentIMP(const char *info, SEL _cmd) {
  IMP imp = NULL;
  if (info[0] == '-' || info[0] == '+') {
    NSString *tmp = [NSString stringWithCString:info+2 encoding:NSUTF8StringEncoding];
    NSRange r = [tmp rangeOfString:@" "];
    NSString *className = [tmp substringToIndex:r.location];
    Class thisClass = NSClassFromString(className);
    if (thisClass != nil) {
      Method m = NULL;
      if (info[0] == '+') {
        m = class_getClassMethod(thisClass, _cmd);
      } else {
        m = class_getInstanceMethod(thisClass, _cmd);
      }
      if (m != NULL) {
        imp = method_getImplementation(m);
      }
    }
  }
  return imp;
}

#define CurrentIMP __CurrentIMP(__PRETTY_FUNCTION__, _cmd)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, what&amp;#8217;s going on?  Basically, we&amp;#8217;re parsing a special string that&amp;#8217;s generated by the compiler and then doing a single lookup.  The important bit is the &lt;code&gt;__PRETTY_FUNCTION__&lt;/code&gt;.  This is a built-in &amp;#8220;magic&amp;#8221; value that, when compiled, becomes a very nice-looking description of the current function (it&amp;#8217;s &amp;#8220;pretty&amp;#8221;).&lt;/p&gt;

&lt;p&gt;For a regular C function, &lt;code&gt;__PRETTY_FUNCTION__&lt;/code&gt; becomes a &lt;code&gt;const char*&lt;/code&gt; that includes the name of the function and some type information.  The &lt;code&gt;main()&lt;/code&gt; function has a &lt;code&gt;__PRETTY_FUNCTION__&lt;/code&gt; of this:  &lt;code&gt;"int main(int, const char **)"&lt;/code&gt;.  Ooooo, pretty! :)&lt;/p&gt;

&lt;p&gt;An Objective-C method&amp;#8217;s pretty description doesn&amp;#8217;t include type information, but it does include some very important information.  Let&amp;#8217;s say we have a class &lt;code&gt;Bar&lt;/code&gt; that has this method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (id)doAwesomeThingWithFoo:(Foo *)foo {
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The pretty description for this is &lt;code&gt;"-[Bar doAwesomeThingWithFoo:]"&lt;/code&gt;.  Here, we see two very important pieces of information:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;The first character is a &lt;code&gt;-&lt;/code&gt;, indicating that the method is an instance method&lt;/li&gt;
&lt;li&gt;The name of the implementing class is clearly visible.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;The selector is also in there, but we would have that anyway through &lt;code&gt;_cmd&lt;/code&gt;, so that&amp;#8217;s not very interesting.  (We could forego passing in &lt;code&gt;_cmd&lt;/code&gt; to the &lt;code&gt;__CurrentIMP&lt;/code&gt; function and parse it out of the description, but since &lt;code&gt;_cmd&lt;/code&gt; is there already, let&amp;#8217;s use that.)&lt;/p&gt;

&lt;p&gt;The really important thing to realize here is that the name of the class in the description is &lt;em&gt;the class on which the method is implemented&lt;/em&gt;, and &lt;strong&gt;not&lt;/strong&gt; the class of any instance.  This makes sense, because this is all happening at compile time, not runtime.&lt;/p&gt;

&lt;p&gt;Armed with these two pieces of information, we can quickly get the appropriate &lt;code&gt;IMP&lt;/code&gt;.  First, we do some really simple string parsing to extract the name of the class from the description, and turn it in to a &lt;code&gt;Class&lt;/code&gt; object with the &lt;code&gt;NSClassFromString&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;Now that we have the &lt;code&gt;Class&lt;/code&gt; and the selector (we&amp;#8217;re just using &lt;code&gt;_cmd&lt;/code&gt;), we can get the &lt;code&gt;IMP&lt;/code&gt;.  However, we need to know which runtime function we should be using.  For this, we can simply look at the first character in the description string.  If it&amp;#8217;s a &lt;code&gt;+&lt;/code&gt;, then we use the class-specific function, otherwise we&amp;#8217;ll use the instance-specific function.&lt;/p&gt;

&lt;p&gt;These functions (&lt;code&gt;class_getClassMethod&lt;/code&gt; and &lt;code&gt;class_getInstanceMethod&lt;/code&gt;) both return &lt;code&gt;Method&lt;/code&gt; references.  From this &lt;code&gt;Method&lt;/code&gt;, we can simply use &lt;code&gt;method_getImplemention&lt;/code&gt; to get the method&amp;#8217;s &lt;code&gt;IMP&lt;/code&gt;.  Simple!&lt;/p&gt;

&lt;p&gt;Some may ask: why are we getting the &lt;code&gt;Method&lt;/code&gt; reference instead of using the &lt;code&gt;class_getMethodImplementation&lt;/code&gt; function, which returns an &lt;code&gt;IMP&lt;/code&gt; directly?  The answer for that is that while that would usually work, it would fail for methods that have large return values (i.e. where the size of the return value is larger than &lt;code&gt;sizeof(id)&lt;/code&gt;).  In that case, we&amp;#8217;d have to use the &lt;code&gt;class_getMethodImplementation_stret&lt;/code&gt; function, which means we&amp;#8217;d have to get an &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMethodSignature_Class/Reference/Reference.html"&gt;&lt;code&gt;NSMethodSignature&lt;/code&gt;&lt;/a&gt; object and check the &lt;code&gt;methodReturnLength&lt;/code&gt; to decide which function to use.  I figure that getting the &lt;code&gt;Method&lt;/code&gt; and asking it for its &lt;code&gt;IMP&lt;/code&gt; is probably simpler.&lt;/p&gt;

&lt;p&gt;Now, there is a downside to this approach (that are not present in Matt&amp;#8217;s implementation).  Since this is relying on a &lt;em&gt;compile time&lt;/em&gt; detail (the pretty description), this totally and utterly breaks when you start add methods, swizzling implementations, make &lt;code&gt;IMP&lt;/code&gt;s from blocks, etc.&lt;/p&gt;

&lt;p&gt;But for those times where you, for whatever reason, need to know what your &lt;code&gt;IMP&lt;/code&gt; is, this works pretty well.&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;&lt;a href="http://bagelturf.com"&gt;Steve Weller&lt;/a&gt; pointed on &lt;a href="https://twitter.com/#!/bagelturf/status/143135189881724928"&gt;on Twitter&lt;/a&gt; that if you combine this code with Matt&amp;#8217;s version, you can reasonably determine when a method has been swizzled.  Cool!&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/13703791542</link><guid>http://funwithobjc.tumblr.com/post/13703791542</guid><pubDate>Sat, 03 Dec 2011 17:16:32 -0800</pubDate><category>runtime</category></item><item><title>Dumbfounded</title><description>&lt;p&gt;I was just shown an &lt;code&gt;NSPredicate&lt;/code&gt; that dumbfounded me for several reasons:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;It&amp;#8217;s using five nested &lt;code&gt;SUBQUERY&lt;/code&gt; expressions.  In other words, a &lt;code&gt;SUBQUERY&lt;/code&gt; within a &lt;code&gt;SUBQUERY&lt;/code&gt; within a &lt;code&gt;SUBQUERY&lt;/code&gt; within a &lt;code&gt;SUBQUERY&lt;/code&gt; within a &lt;code&gt;SUBQUERY&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;It works&lt;/li&gt;
&lt;li&gt;It&amp;#8217;s reasonably fast&lt;/li&gt;
&lt;li&gt;Core Data correctly handles it on a SQLite store&lt;/li&gt;
&lt;li&gt;It&amp;#8217;s the only way the author could accomplish what he needed in a &amp;#8220;reasonable&amp;#8221; way.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;What sort of &lt;code&gt;NSPredicate&lt;/code&gt; is this?  Here you go:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static NSString *kCommonRequestFragment = @"SUBQUERY(things, $thing, SUBQUERY($thing.thingType.spams, $spam, SUBQUERY($spam.ham.eggs, $egg, SUBQUERY($egg.foo.bars, $bar, SUBQUERY($bars.baz.blips, $blip, $blip.bing.id == %@).@count &amp;gt; 0).@count &amp;gt; 0).@count &amp;gt; 0).@count &amp;gt; 0).@count &amp;gt; 0";

- (NSFetchRequest *)fetchRequestForSomeObjects {
    NSFetchRequest *theRequest = [self templateFetchRequest];
    NSString * thePredicateFormatString = [NSString stringWithFormat:@"(%@) AND (%@)", @"SUBQUERY(participatingObjects, $object, $object.property.id == %@).@count &amp;gt; 0", kCommonRequestFragment];
    [theRequest setPredicate:[NSPredicate predicateWithFormat:thePredicateFormatString, self.aThing.anID, self.aThing.anotherID]];

    return theRequest;
}

- (NSFetchRequest *)fetchRequestForOtherObjects {
    NSFetchRequest *theRequest = [self templateFetchRequest];
    NSString * thePredicateFormatString = [NSString stringWithFormat:@"(%@) AND (%@)", @"SUBQUERY(participatingObjects, $object, $object.property.id == %@).@count == 0", kCommonRequestFragment];
    [theRequest setPredicate:[NSPredicate predicateWithFormat:thePredicateFormatString, self.aThing.anID, self.aThing.anotherID]];

    return theRequest;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Insane.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/7289992438</link><guid>http://funwithobjc.tumblr.com/post/7289992438</guid><pubDate>Tue, 05 Jul 2011 20:39:03 -0700</pubDate><category>nspredicate</category></item><item><title>Parsing Mathematical Expressions</title><description>&lt;p&gt;A while ago, I was looking for a library to parse &lt;code&gt;NSString&lt;/code&gt; objects as mathematical expressions.  I wanted to be able to take a string like &lt;code&gt;@"2+3*4"&lt;/code&gt; and get back &lt;code&gt;14&lt;/code&gt;.  I found two easy ways to do this:  &lt;code&gt;GCMathParser&lt;/code&gt; and &lt;code&gt;NSPredicate&lt;/code&gt; (of course!).&lt;/p&gt;

&lt;p&gt;&lt;a href="http://apptree.net/parser.htm"&gt;&lt;code&gt;GCMathParser&lt;/code&gt;&lt;/a&gt; is a library by Graham Cox for parsing strings as equations.  It uses a parser generated by &lt;a href="http://www.gnu.org/software/bison/"&gt;BISON&lt;/a&gt; as the primary engine, with a straight-forward Objective-C wrapper for easy interaction.  In terms of raw speed, it&amp;#8217;s blazingly fast.  However, I found one major flaw with it: it is impossible to extend.  It has support for a bunch of built-in functions (all your basic trigonometric functions, rounding, etc), but if you wanted to add support for bitwise operators (bitwise AND, OR, NOT, XOR, etc), you&amp;#8217;re totally out of luck.  There&amp;#8217;s no way to do it without regenerating an entirely new parser.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NSPredicate&lt;/code&gt;, &lt;a href="http://funwithobjc.tumblr.com/post/1553469975/abusing-nspredicate"&gt;as I&amp;#8217;ve mentioned before&lt;/a&gt;, can also parse numerical expressions.  Like &lt;code&gt;GCMathParser&lt;/code&gt;, it has a couple of flaws:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;The associativity of the power operator is wrong.  The string &lt;code&gt;@"2 ** 3 ** 2"&lt;/code&gt; is parsed as &lt;code&gt;(2 ** 3) ** 2&lt;/code&gt;, or &lt;code&gt;64&lt;/code&gt;.  This is &amp;#8220;left associativity&amp;#8221;.  In practical terms, it means that when you have a bunch of the same operator in a row like that, the left-most one is evaluated first.  However, &lt;a href="http://en.wikipedia.org/wiki/Exponentiation#Identities_and_properties"&gt;exponentiation is supposed to be right associative&lt;/a&gt;.  In other words, that expression should&amp;#8217;ve been parsed as &lt;code&gt;2 ** (3 ** 2)&lt;/code&gt;, or &lt;code&gt;512&lt;/code&gt;.  This is a major flaw, and it&amp;#8217;s been reported: &lt;a href="rdar://8692313"&gt;rdar://8692313&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;The syntax for custom functions is absurdly bizarre.  &lt;code&gt;NSExpression&lt;/code&gt;, the class that makes up the basic components of a predicate, does not have any trigonometric functions built-in.  However, &lt;code&gt;NSExpression&lt;/code&gt; does support defining your own functions, but with a &lt;a href="http://funwithobjc.tumblr.com/post/2922267976/using-custom-functions-with-nsexpression"&gt;ridiculously complex syntax&lt;/a&gt;.  For my purposes, I wanted to take a regular user-entered string and parse it, without requiring the user to know about &lt;code&gt;FUNCTION()&lt;/code&gt; syntax.  I could&amp;#8217;ve tried manipulating the user&amp;#8217;s string to transform &lt;code&gt;sin(&amp;lt;#expression#&amp;gt;)&lt;/code&gt; into &lt;code&gt;FUNCTION(&amp;lt;#expression#&amp;gt;, 'sinValue')&lt;/code&gt; and then written a &lt;code&gt;sinValue&lt;/code&gt; category method on &lt;code&gt;NSNumber&lt;/code&gt;, but if I was going to write a transformer to manipulate the string, I might as well write a full-fledged parser.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;So, I wrote &lt;a href="https://github.com/davedelong/DDMathParser"&gt;&lt;code&gt;DDMathParser&lt;/code&gt;&lt;/a&gt; to be extensible, correct, and easy to understand.&lt;/p&gt;

&lt;h2&gt;The Guts&lt;/h2&gt;

&lt;p&gt;I tried writing a formal grammar for parsing a mathematical expression, and actually &lt;a href="https://github.com/davedelong/DDMathParser/blob/master/MathGrammar.grammar"&gt;got pretty far&lt;/a&gt;.  However, when writing the &lt;a href="http://en.wikipedia.org/wiki/Recursive_descent_parser"&gt;recursive descent parser&lt;/a&gt; to match strings against this grammar, I came up against some conceptual hurdles that I couldn&amp;#8217;t work around.  I also didn&amp;#8217;t like that modifying the grammar, even slightly, usually meant making extremely large changes to the parser.  Eventually I gave up with that sort of parser and came up with something else.&lt;/p&gt;

&lt;p&gt;There are several phases to parsing a string using this parser:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Tokenization&lt;/li&gt;
&lt;li&gt;Grouping&lt;/li&gt;
&lt;li&gt;Resolving&lt;/li&gt;
&lt;/ol&gt;&lt;h3&gt;Tokenization&lt;/h3&gt;

&lt;p&gt;Tokenization is simply the process of breaking up the string into chunks.  If I have the string &lt;code&gt;@"1 + 2 - 3 * 4 / 5"&lt;/code&gt;, then after tokenization I&amp;#8217;m going to end up with 9 tokens: &lt;code&gt;1&lt;/code&gt;, &lt;code&gt;+&lt;/code&gt;, &lt;code&gt;2&lt;/code&gt;, &lt;code&gt;-&lt;/code&gt;, &lt;code&gt;3&lt;/code&gt;, &lt;code&gt;*&lt;/code&gt;, &lt;code&gt;4&lt;/code&gt;, &lt;code&gt;/&lt;/code&gt;, and &lt;code&gt;5&lt;/code&gt;.  No attempt is made to try to resolve anything.  I will note, however, that this is the point at which implicit multiplication is made explicit.  More on that later.&lt;/p&gt;

&lt;p&gt;The tokenization process simply reads through the string character-by-character, and decides what to do with the characters it finds.  The general rules it follows are:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;If it reads a digit or a decimal point, attempt to parse a number (a number is defined as anything recognizable by &lt;code&gt;NSNumberFormatter&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;If parsing a number failed and the character is matched by &lt;code&gt;[a-zA-Z0-9]&lt;/code&gt; (any alphanumeric character), then attempt to parse the name of a function.&lt;/li&gt;
&lt;li&gt;If parsing a function name failed and the character is the &lt;code&gt;$&lt;/code&gt; character, then attempt to parse a variable name.&lt;/li&gt;
&lt;li&gt;If parsing a variable name failed, then attempt to parse an operator.&lt;/li&gt;
&lt;li&gt;If parsing an operator failed, then abort with an error.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;It&amp;#8217;s also at this point that we figure out if &lt;code&gt;-&lt;/code&gt; and &lt;code&gt;+&lt;/code&gt; are acting, for example, as negation or subtraction.  The basic rule is: if a &lt;code&gt;-&lt;/code&gt; or &lt;code&gt;+&lt;/code&gt; is preceded by another operator that&amp;#8217;s not a closing parenthesis (or it&amp;#8217;s the first token in the steam), then it&amp;#8217;s the unary operator (negation, etc).  Otherwise it&amp;#8217;s the binary operator.&lt;/p&gt;

&lt;h3&gt;Grouping&lt;/h3&gt;

&lt;p&gt;If tokenization succeeds, the tokens are grouped into &amp;#8220;terms&amp;#8221;.  To explain what goes on, we&amp;#8217;ll look at an example.  Let&amp;#8217;s say we&amp;#8217;re parsing the string &lt;code&gt;@"2 * (pi()sin(dtor(45)) + max($a, 42)/54)"&lt;/code&gt;.  The token stream will have generated these tokens:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;2 * ( pi ( ) * sin ( dtor ( 45 ) ) + max ( $a , 42 ) / 54 )
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Grouping organizes the terms hierarchically.  This is done recursively, and is also where parentheses are checked to make sure they&amp;#8217;re balanced.  Visually, we&amp;#8217;ll end up with something like this:&lt;/p&gt;

&lt;center&gt;
&lt;img src="http://gallery.me.com/davedelong/100129/Grouping1_1/web.png?ver=13072394490001" alt="First phase of grouping"/&gt;&lt;/center&gt;

&lt;p&gt;As you can see, no attempt has been made to define precedence.  The step is only to break up the tokens into parenthetical &amp;#8220;levels&amp;#8221;.&lt;/p&gt;

&lt;h3&gt;Resolving&lt;/h3&gt;

&lt;p&gt;After the terms have been grouped, we can break things up further.  We take the root group and iterate over the terms in its &amp;#8220;&lt;code&gt;subterms&lt;/code&gt;&amp;#8221; array to find the indices of the operators with &lt;a href="http://en.wikipedia.org/wiki/Operator_precedence"&gt;the highest precedence&lt;/a&gt;.  Precedence is defined via an &lt;code&gt;enum&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;enum {
    DDPrecedenceBitwiseOr = 0,
    DDPrecedenceBitwiseXor,
    DDPrecedenceBitwiseAnd,
    DDPrecedenceLeftShift,
    DDPrecedenceRightShift,
    DDPrecedenceSubtraction,
    DDPrecedenceAddition = DDPrecedenceSubtraction,
    DDPrecedenceDivision,
    DDPrecedenceMultiplication = DDPrecedenceDivision,
    DDPrecedenceModulo,
    DDPrecedenceUnary,
    DDPrecedenceFactorial,
    DDPrecedencePower,
    DDPrecedenceParentheses,

    DDPrecedenceUnknown = -1,
    DDPrecedenceNone = -2
};
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Parentheses produce the highest precedence, followed by the power operator, then the factorial operator, then any generic unary operator (negation, bitwise NOR, etc), and then down on through the standard mathematical operators, with bitwise OR having the lowest precedence.  Subtraction has the same precedence as addition, since subtraction is really just the addition of a negative number.  Likewise, division is the same as multiplication by the number&amp;#8217;s multiplicative inverse.&lt;/p&gt;

&lt;p&gt;Once we have the indices of the operators with the highest precedence, we&amp;#8217;ll need to look and see if we have more than one.  If we do, then we look at the associativity of the operator to see if we should choose the first (ie, left associative) or last (ie, right associative) operator.  After picking an operator, we can look at the terms around the operator, recursively resolve those terms (if necessary), and then combine those resolved terms and the operator into a new group term.  This is when we check to make sure that operators have all the necessary terms.  It&amp;#8217;s at this point, for example, that &lt;code&gt;@"2+"&lt;/code&gt; would fail to parse, because &lt;code&gt;+&lt;/code&gt; is a binary operator, but the string only has a single term.  &lt;code&gt;@"+2"&lt;/code&gt;, however, &lt;em&gt;would&lt;/em&gt; parse, because &lt;code&gt;+&lt;/code&gt; would already have been recognized as a unary operator.&lt;/p&gt;

&lt;p&gt;After resolution has finished, our object hierarchy now looks like this:&lt;/p&gt;

&lt;center&gt;
&lt;img src="http://gallery.me.com/davedelong/100129/Grouping2_1/web.png?ver=13072394500001" alt="After term resolution"/&gt;&lt;/center&gt;

&lt;p&gt;At this point, the term hierarchy is fully organized, and it&amp;#8217;s a simple matter to convert it into expression objects for storage and/or evaluation.&lt;/p&gt;

&lt;h2&gt;Implicit Multiplication&lt;/h2&gt;

&lt;p&gt;When writing mathematical expressions, we understand that we can express the multiplication of two terms without actually writing a multiplication operator.  For example, &lt;code&gt;5x&lt;/code&gt; is &lt;code&gt;5 * x&lt;/code&gt;, and &lt;code&gt;6(9)&lt;/code&gt; is the same thing as &lt;code&gt;6 * 9&lt;/code&gt;.  I really wanted the parser to handle implicit multiplication, and it turns out it was very simple to implement.  When tokenizing a string, a &lt;code&gt;*&lt;/code&gt; token is inserted between two tokens if a Number, Variable, or Close Parenthesis token is followed by anything except an operator token (unless it&amp;#8217;s an Open Parenthesis token).  With this setup:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;5$x&lt;/code&gt; becomes &lt;code&gt;5 * $x&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;6(9)&lt;/code&gt; becomes &lt;code&gt;6 * (9)&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;2sin($x)&lt;/code&gt; becomes &lt;code&gt;2 * sin($x)&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;h2&gt;Analysis&lt;/h2&gt;

&lt;p&gt;As I see it, there are several major advantages to this parser:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;The only limit on valid numbers is that they be recognizable by &lt;code&gt;NSNumberFormatter&lt;/code&gt;.  This means that we can use numerical types with far more precision than a &lt;code&gt;double&lt;/code&gt;, and much larger than a &lt;code&gt;long long&lt;/code&gt;.  For all but the trigonometric functions, calculations are done with &lt;code&gt;NSDecimal&lt;/code&gt; structs boxed in &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDecimalNumber_Class/Reference/Reference.html%23//apple_ref/occ/cl/NSDecimalNumber"&gt;&lt;code&gt;NSDecimalNumber&lt;/code&gt;&lt;/a&gt; objects.&lt;/li&gt;
&lt;li&gt;Function resolution doesn&amp;#8217;t happen until evaluation time.  This allows us to parse strings like &lt;code&gt;bogus(42)&lt;/code&gt;, but not care that the &lt;code&gt;bogus&lt;/code&gt; function doesn&amp;#8217;t exist.  With the ability to delay function recognition, we&amp;#8217;re free to define any extra functions that we want.&lt;/li&gt;
&lt;li&gt;Parsing is not defined by a grammar.  If we need to add a new operator, it&amp;#8217;s very feasible, and won&amp;#8217;t require generating a whole new parser.&lt;/li&gt;
&lt;li&gt;Operator associativity can be changed on-the-fly.  If, for some reason, you need exponentiation to be left associative rather than right associative, it&amp;#8217;s extremely easy to change that with a simple property change.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;The primary downside of this parser, however, is speed.  Since we&amp;#8217;re operating with several different layers of Objective-C objects, rather than on a C string, there&amp;#8217;s going to be an enormous&lt;sup&gt;*&lt;/sup&gt; speed discrepancy between &lt;code&gt;GCMathParser&lt;/code&gt; and &lt;code&gt;DDMathParser&lt;/code&gt;.  However, what we lose in speed is more than made up for in extensibility and accuracy.&lt;/p&gt;

&lt;p&gt;The code is available for your perusal at GitHub: &lt;a href="https://github.com/davedelong/DDMathParser"&gt;https://github.com/davedelong/DDMathParser&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;sup&gt;* by &amp;#8220;enormous&amp;#8221;, I mean &amp;#8220;about 2 orders of magnitude, but still able to parse and evaluate a complex string in a fraction of a second&amp;#8221;&lt;/sup&gt;&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;&lt;strong&gt;Updates&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;4 Jun 2011: original posting&lt;/li&gt;
&lt;li&gt;5 Jun 2011: added description of recognizing unary operators&lt;/li&gt;
&lt;/ul&gt;</description><link>http://funwithobjc.tumblr.com/post/6196535272</link><guid>http://funwithobjc.tumblr.com/post/6196535272</guid><pubDate>Sun, 05 Jun 2011 10:10:43 -0700</pubDate><category>parser</category><category>math</category></item><item><title>Subclassing NSInputStream</title><description>&lt;p&gt;Subclassing &lt;code&gt;NSInputStream&lt;/code&gt; is a problem that has been plaguing Cocoa developers for a long time.  &lt;a href="http://www.google.com/search?q=subclass+nsinputstream"&gt;Googling &amp;#8220;subclass nsinputstream&amp;#8221;&lt;/a&gt; reveals that people have been having issues with this for six or seven years.  While &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSInputStream_Class/Reference/Reference.html"&gt;the documentation&lt;/a&gt; seems to indicate that it should be fairly straightforward, actually trying to do so reveals several hairy spots.&lt;/p&gt;

&lt;p&gt;For example, if you try to use a custom &lt;code&gt;NSInputStream&lt;/code&gt; as the body of an &lt;code&gt;NSURLRequest&lt;/code&gt;, you&amp;#8217;ll get an exception that your input stream doesn&amp;#8217;t respond to &lt;code&gt;_scheduleInCFRunLoop:forMode:&lt;/code&gt;.  So then you create an empty stub for that method.  You&amp;#8217;re good, right?  Nope!  Now you fail with an unimplemented &lt;code&gt;_setCFClientFlags:callback:context:&lt;/code&gt;.  So you implement &lt;em&gt;that&lt;/em&gt;, and you&amp;#8217;re good, right?  Nope!  You fail now with an unimplemented &lt;code&gt;_unscheduleFromCFRunLoop:forMode:&lt;/code&gt;.  So you put &lt;em&gt;that&lt;/em&gt; in as a stub, and you&amp;#8217;re good?  Well, you don&amp;#8217;t get any more exceptions&amp;#8230; but nothing ever gets read from your stream.  Minor details&amp;#8230;&lt;/p&gt;

&lt;p&gt;Well, the dark night of ignorance and inability is over!&lt;/p&gt;

&lt;p&gt;BJ Homer has just posted &lt;a href="http://bjhomer.blogspot.com/2011/04/subclassing-nsinputstream.html"&gt;an article on how he got his &lt;code&gt;NSInputStream&lt;/code&gt; subclass to work&lt;/a&gt;.  He&amp;#8217;s even &lt;a href="https://github.com/bjhomer/HSCountingInputStream"&gt;posted a demo on his GitHub account&lt;/a&gt;.  I won&amp;#8217;t spoil any of the details here; go read it for yourself! His solution is really quite clever.&lt;/p&gt;

&lt;p&gt;(And as a side note, at the time of this writing, there are 2,272 occurrences of the letter &amp;#8216;n&amp;#8217; on his blog&amp;#8217;s home page.)&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/4626637919</link><guid>http://funwithobjc.tumblr.com/post/4626637919</guid><pubDate>Thu, 14 Apr 2011 21:57:22 -0700</pubDate><category>nsinputstream</category></item><item><title>How to learn Cocoa</title><description>&lt;p&gt;This is something any experienced Cocoa developer has been asked at least half a dozen times:&lt;/p&gt;

&lt;p&gt;&amp;#8220;What&amp;#8217;s the best way to learn Objective-C/Cocoa?&amp;#8221;&lt;/p&gt;

&lt;p&gt;I have two answers to this question:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Be curious&lt;/li&gt;
&lt;li&gt;Don&amp;#8217;t be satisfied&lt;/li&gt;
&lt;/ol&gt;&lt;h2&gt;Be Curious&lt;/h2&gt;

&lt;p&gt;Curiosity is the heart of learning &lt;em&gt;anything&lt;/em&gt;.  If you can cultivate a deep curiosity about the Objective-C language and the Cocoa frameworks, then I guarantee that you will have absolutely no problem learning them.  I&amp;#8217;m not talking about the &amp;#8220;oh, wouldn&amp;#8217;t it be nice to know how to write iOS apps&amp;#8221; kind of curiosity.  I&amp;#8217;m talking about the &amp;#8220;why does the &lt;code&gt;@&lt;/code&gt; sign go there?  What&amp;#8217;s up with these asterisks all over the place?  Why are things done in &lt;em&gt;this&lt;/em&gt; order instead of &lt;em&gt;that&lt;/em&gt; order&amp;#8221; kind of curiosity.  Gaining this level of curiosity can be very difficult, especially at first.  But without it, you&amp;#8217;ll never really understand how everything is working together.&lt;/p&gt;

&lt;p&gt;If you&amp;#8217;re familiar with an sort of object-oriented programming language, then Objective-C, as a language, shouldn&amp;#8217;t be that hard to pick up.  Just use get used to the square brackets, and things will look pretty familiar.  Learning the frameworks, on the other hand, will take a lifetime.  The Cocoa Frameworks (Foundation, AppKit/UIKit, CoreData, CoreFoundation, MapKit, QuickLook, MediaAccess, CoreLocation, etc) are enormously broad.  The &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/ObjC_classic/_index.html"&gt;Foundation framework&lt;/a&gt; itself is composed of 173 public classes and 31 protocols.  That&amp;#8217;s a &lt;em&gt;lot&lt;/em&gt; of pre-built code, and that&amp;#8217;s just one framework out of a couple dozen!  There are some classes you will come to know very intimately (&lt;code&gt;NSString&lt;/code&gt;, &lt;code&gt;NSArray&lt;/code&gt;, &lt;code&gt;NSDictionary&lt;/code&gt;), but even they will surprise you every now and then.  Plus, Apple actively develops these frameworks; they&amp;#8217;re being improved and optimized and expanded all the time.  There will always be more to learn.&lt;/p&gt;

&lt;p&gt;Along with the capabilities of the classes, there are &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html"&gt;patterns to learn&lt;/a&gt;.  Design patterns describe how classes interact with each other.  Some of the first ones you&amp;#8217;ll encounter are &lt;a href="http://developer.apple.com/library/ios/#documentation/general/conceptual/DevPedia-CocoaCore/MVC.html"&gt;Model View Controller&lt;/a&gt;, &lt;a href="http://developer.apple.com/library/ios/#documentation/general/conceptual/DevPedia-CocoaCore/Delegation.html"&gt;Delegation&lt;/a&gt;, and &lt;a href="http://developer.apple.com/library/ios/#documentation/general/conceptual/DevPedia-CocoaCore/ClassCluster.html"&gt;Class Clusters&lt;/a&gt;.  There are many others, and they&amp;#8217;re in there for a very good reason.  As you come across them, take the time to understand why they&amp;#8217;re there.&lt;/p&gt;

&lt;p&gt;Do the same with the classes in the frameworks.  Explore them.  Play with them.  Abuse them.  Ask yourself:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;What problem does this solve?&lt;/li&gt;
&lt;li&gt;How does it solve the problem?&lt;/li&gt;
&lt;li&gt;Can you use these abilities for anything else?&lt;/li&gt;
&lt;li&gt;How would &lt;em&gt;you&lt;/em&gt; implement this class if you had to?  (And then go do it!)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Be curious.&lt;/p&gt;

&lt;h2&gt;Don&amp;#8217;t Be Satisfied&lt;/h2&gt;

&lt;p&gt;As you learn Cocoa, the code you write will be terrible.  Understand that.  But don&amp;#8217;t accept it.  There is always a different way you could do something, and quite often one of those different ways is a better way.  Always seek out opportunities to improve your code and to find different and better ways to organize it.  Sometimes this will mean rewriting things half a dozen times.  But you know what?  That&amp;#8217;s OK!  All developers experience this.  If you can learn to not be satisfied with your code, you&amp;#8217;ll quickly learn how to iterate over it and make improvements here, tweak some stuff there, maybe rip out some layer of control and totally reorganize it&amp;#8230;  This is what programming is all about.  Don&amp;#8217;t be satisfied with how your code looks.  Strive to make it a work of art and a thing of beauty.&lt;/p&gt;

&lt;h2&gt;Final Thoughts&lt;/h2&gt;

&lt;p&gt;So there you have it!  These are my recommendations for how to learn Cocoa.  They have served me well, and I think they pretty much summarize what I&amp;#8217;ve observed about experienced developers.&lt;/p&gt;

&lt;p&gt;Oh, and by the way&amp;#8230;&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Know what a pointer is.&lt;/li&gt;
&lt;li&gt;Memorize the memory management rules.&lt;/li&gt;
&lt;li&gt;Never invoke &lt;code&gt;-retainCount&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Welcome to Cocoa.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/3956963435</link><guid>http://funwithobjc.tumblr.com/post/3956963435</guid><pubDate>Sat, 19 Mar 2011 01:38:15 -0700</pubDate><category>learning</category></item><item><title>How I do my singletons</title><description>&lt;p&gt;This is something that comes up again and again.  How do you make a true &lt;a href="http://en.wikipedia.org/wiki/Singleton_pattern"&gt;singleton&lt;/a&gt; in Objective-C?  I was just asked this the other night, so I decided to write up my version of an Objective-C singleton.&lt;/p&gt;

&lt;p&gt;For starters, &lt;a href="http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32"&gt;there&amp;#8217;s an example in the documentation&lt;/a&gt; on how you could make a singleton.  It&amp;#8217;s a pretty bizarre implementation.
StackOverflow.com has &lt;a href="http://stackoverflow.com/q/145154/115730"&gt;a nice long discussion&lt;/a&gt; on what people consider acceptable singletons.  Peter Hosey &lt;a href="http://boredzo.org/blog/archives/2009-06-17/doing-it-wrong"&gt;wrote an in-depth post about it a while back&lt;/a&gt; as well, with a different example of what he considers a good singleton.&lt;/p&gt;

&lt;p&gt;Go read those articles, then come back.&lt;/p&gt;

&lt;p&gt;Have you read them yet?  Good.&lt;/p&gt;

&lt;p&gt;I think Peter&amp;#8217;s overview of what makes a singleton is very good.  In particular, he has several criteria that, if met, help define a singleton.  They are:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;code&gt;+sharedFramistan&lt;/code&gt; always returns the same object.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; always produce the same object (which, itself, is the same object as &lt;code&gt;+sharedFramistan&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; will not return an object confused by multiple init messages.&lt;/li&gt;
&lt;li&gt;Over-releasing causes a crash.&lt;/li&gt;
&lt;li&gt;Keeping &lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;+allocWithZone:&lt;/code&gt;/&lt;code&gt;-retain&lt;/code&gt; balanced with &lt;code&gt;release&lt;/code&gt; never causes a crash.&lt;/li&gt;
&lt;li&gt;If &lt;code&gt;[super init]&lt;/code&gt; returns a different object, &lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; won&amp;#8217;t break.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Over the couple years, I&amp;#8217;ve developed my own singleton pattern.  I think it&amp;#8217;s pretty simple, it gets the job done, and it&amp;#8217;s fairly idiot-proof.  It does have a drawback, which is that the singleton exists for the lifetime of the process; it is not lazily created.  If that&amp;#8217;s a problem for you, well then this singleton probably isn&amp;#8217;t for you.  Other than that, it has served me very well.&lt;/p&gt;

&lt;p&gt;So, without further ado, here it is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// DDFramistan.h
@interface DDFramistan : NSObject

+ (id) sharedFramistan;

@end

// DDFramistan.m

static DDFramistan *_sharedFramistan = nil;

__attribute__((constructor)) static void construct_singleton() {
  NSAutoreleasePool * p = [[NSAutoreleasePool alloc] init];
  _sharedFramistan = NSAllocateObject([DDFramistan class], 0, nil);
  [p drain];
}

__attribute__((destructor)) static void destroy_singleton() {
  NSAutoreleasePool * p = [[NSAutoreleasePool alloc] init];
  NSDeallocateObject(_sharedFramistan), _sharedFramistan = nil;
  [p drain];
}

@implementation DDFramistan

+ (id)sharedFramistan {
  return _sharedFramistan;
}

+ (id) allocWithZone:(NSZone *)zone {
  return [[DDFramistan sharedFramistan] retain];
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The only really weird things going on here are those two functions, &lt;code&gt;construct_singleton()&lt;/code&gt; and &lt;code&gt;destroy_singleton()&lt;/code&gt;.  What&amp;#8217;s up with those?  Basically, by tacking that &lt;code&gt;__attribute__((constructor))&lt;/code&gt; onto the function declaration, this function will get invoked &lt;em&gt;before execution enters &lt;code&gt;main()&lt;/code&gt;&lt;/em&gt;.  As such, we have to set up an &lt;code&gt;NSAutoreleasePool&lt;/code&gt; for the off-chance that we happen to create any autoreleased objects during singleton creation.  Also, I&amp;#8217;m using the &lt;a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/doc/uid/20000055-BCIHCIIB"&gt;&lt;code&gt;NSAllocateObject()&lt;/code&gt;&lt;/a&gt; function, which is pretty much the same thing as &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html%23//apple_ref/c/func/class_createInstance"&gt;&lt;code&gt;class_createInstance()&lt;/code&gt;&lt;/a&gt;.  That&amp;#8217;s going to allocate a new object for me on the heap, with all of the members of that object set to &lt;code&gt;0&lt;/code&gt; (ie, it&amp;#8217;s essentially using &lt;code&gt;calloc()&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Similarly, the &lt;code&gt;__attribute__((destructor))&lt;/code&gt; function is one that will get executed after returning from &lt;code&gt;main()&lt;/code&gt; (or &lt;code&gt;exit()&lt;/code&gt;).  This one isn&amp;#8217;t quite as necessary, since if the program is exiting, all the memory is going to get cleaned up anyway.  However, if you&amp;#8217;ve got shared resources (file descriptors, etc), this would be the place to clean them up.  Again, we wrap the deallocation in an &lt;code&gt;NSAutoreleasePool&lt;/code&gt; to catch any autoreleased objects that may get created in the process (which would be weird, but not impossible).&lt;/p&gt;

&lt;p&gt;As for the methods on the singleton itself, they&amp;#8217;re really straight forward:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;+sharedFramistan&lt;/code&gt; returns our singleton&lt;/li&gt;
&lt;li&gt;&lt;code&gt;+allocWithZone:&lt;/code&gt; returns the static singleton, retained (&lt;a href="http://developer.apple.com/library/mac/documentation/cocoa/conceptual/MemoryMgmt/Articles/mmObjectOwnership.html#//apple_ref/doc/uid/20000043-SW1"&gt;just like it&amp;#8217;s supposed to&lt;/a&gt;)&lt;/li&gt;
&lt;li&gt;Since we have no &lt;code&gt;-init&lt;/code&gt; method, we&amp;#8217;ll simply inherit the one belonging to &lt;code&gt;NSObject&lt;/code&gt;.  &lt;code&gt;-[NSObject init]&lt;/code&gt; &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocAllocInit.html%23//apple_ref/doc/uid/TP30001163-CH22-SW2"&gt;is documented to simply &lt;code&gt;return self&lt;/code&gt;&lt;/a&gt;, so we&amp;#8217;re safe to invoke it as many times as we want.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Other than that, it&amp;#8217;s a perfectly normal Objective-C object.  Let&amp;#8217;s go over Peter&amp;#8217;s list and see how we did:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;p&gt;&lt;code&gt;+sharedFramistan&lt;/code&gt; always returns the same object.&lt;br/&gt;
Yep, we got that.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; always produce the same object (which, itself, is the same object as &lt;code&gt;+sharedFramistan&lt;/code&gt;).&lt;br/&gt;
Yep, we got that too.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; will not return an object confused by multiple init messages.&lt;br/&gt;
Since the init method does &lt;em&gt;do&lt;/em&gt; anything, this is easily accomplished.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Over-releasing causes a crash.&lt;br/&gt;
We&amp;#8217;re not doing anything bizarre with memory management, so if you over-release the singleton, it will get deallocated prematurely, and accessing it after that &lt;em&gt;will&lt;/em&gt; cause your program to crash.  So&amp;#8230; check.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Keeping &lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;+allocWithZone:&lt;/code&gt;/&lt;code&gt;-retain&lt;/code&gt; balanced with &lt;code&gt;release&lt;/code&gt; never causes a crash.&lt;br/&gt;
Again, we&amp;#8217;re good here.  As long as you don&amp;#8217;t over-release, this object will never go away.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If &lt;code&gt;[super init]&lt;/code&gt; returns a different object, &lt;code&gt;+alloc&lt;/code&gt;/&lt;code&gt;-init&lt;/code&gt; won&amp;#8217;t break.&lt;br/&gt;
Since we don&amp;#8217;t implement &lt;code&gt;-init&lt;/code&gt;, we don&amp;#8217;t have to worry about this.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Looks pretty good!&lt;/p&gt;

&lt;p&gt;Now, the moment we&amp;#8217;ve all been waiting for&amp;#8230;&lt;/p&gt;

&lt;p&gt;Is &lt;code&gt;DDFramistan&lt;/code&gt; a true singleton?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;NO&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;DDFramistan&lt;/code&gt; is &lt;em&gt;not&lt;/em&gt; a true singleton.  A true singleton would never allow another instance of the object to be created under any circumstances.  Unfortunately, Objective-C has fun things like &lt;code&gt;NSAllocateObject()&lt;/code&gt; and &lt;code&gt;class_createInstance()&lt;/code&gt; that allow us to easily bypass all of the normal object creation business, and there&amp;#8217;s nothing we can do about that (that I can think of).  So while it&amp;#8217;s unlikely that you would ever create another instance of &lt;code&gt;DDFramistan&lt;/code&gt;, it&amp;#8217;s not impossible.  And therefore, this is not a true singleton.&lt;/p&gt;

&lt;p&gt;But it&amp;#8217;s probably good enough (and it&amp;#8217;s about as close as you can get).&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;&lt;strong&gt;History&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;24 Feb 2011 - Original post&lt;/li&gt;
&lt;li&gt;24 Feb 2011 - removed unnecessary init method, as suggested in the comments&lt;/li&gt;
&lt;/ul&gt;</description><link>http://funwithobjc.tumblr.com/post/3478903440</link><guid>http://funwithobjc.tumblr.com/post/3478903440</guid><pubDate>Thu, 24 Feb 2011 02:14:54 -0800</pubDate><category>singleton</category></item><item><title>Why do Strings in Objective-C have to be preceded with an @?</title><description>&lt;p&gt;Simple: because if you left it off, it wouldn’t be an &lt;code&gt;NSString*&lt;/code&gt;.  It’d be a &lt;code&gt;char *&lt;/code&gt;.  Any time you see the &lt;code&gt;@&lt;/code&gt; symbol in Objective-C code, you can know that it’s so that the compiler can do something special there that C doesn’t natively support.&lt;/p&gt;

&lt;p&gt;So with that in mind, we have:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;@catch&lt;/code&gt;: declare a scope for catching a thrown execution&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@class&lt;/code&gt;: forward declare a class&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@compatibility_alias&lt;/code&gt;: specify an alias for a class name&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@dynamic&lt;/code&gt;: specify that property accessors will by dynamically implemented at runtime&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@encode&lt;/code&gt;: ask for a character array representing the type of a variable&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@end&lt;/code&gt;: close an interface declaration or an implementation block&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@finally&lt;/code&gt;: declare code that will be executed after an &lt;code&gt;@try&lt;/code&gt; and/or &lt;code&gt;@catch&lt;/code&gt; block execute&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@implementation&lt;/code&gt;: implement a class definition&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@interface&lt;/code&gt;: define a class API (also used for categories and class extensions)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@optional&lt;/code&gt;: declare the optional nature of protocol methods&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@package&lt;/code&gt;: declare the scope of ivars&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@private&lt;/code&gt;: declare the scope of ivars&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@property&lt;/code&gt;: declare a class property&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@protected&lt;/code&gt;: declare the scope of ivars&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@protocol&lt;/code&gt;: declare a list of methods that conforming objects might implement&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@public&lt;/code&gt;: declare the scope of ivars&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@required&lt;/code&gt;: declare the required nature of protocol methods&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@selector&lt;/code&gt;: declare the the stuff that immediately follows in the parentheses is a method name&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@synchronized&lt;/code&gt;: declare a section of code that is atomic&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@synthesize&lt;/code&gt;: direct the compiler to generate accessor methods for properties (that you haven’t implemented yourself)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@throw&lt;/code&gt;: throw an &lt;code&gt;NSException&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@try&lt;/code&gt;: begin a block in which an exception might be thrown&lt;/li&gt;
&lt;li&gt;&lt;code&gt;@""&lt;/code&gt;: declare a constant string&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;That’s all I can remember off the top of my head.  I’m sure I’ve forgotten one or two.  A more complete list (with better explanations) can be found &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocLanguageSummary.html"&gt;in the documentation&lt;/a&gt;.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/3480362644</link><guid>http://funwithobjc.tumblr.com/post/3480362644</guid><pubDate>Thu, 24 Feb 2011 00:55:00 -0800</pubDate></item><item><title>Since this is an Obj-c blog,I have a question for you&lt;br /&gt;&#13;
&lt;br /&gt;&#13;
why would they make another C with OOP,what's wrong with C++?</title><description>&lt;p&gt;It sounds from your question like Objective-C has only been around for a couple years.  Believe it or not, Objective-C is an old language!  It was invented in 1986 by Tom Love and Brad Cox (only 3 years after C++).  It was adopted by NeXT as the lingua franca of the NeXT OS, and was the language that Sir Tim Berners-Lee used to write the world’s first web browser.&lt;/p&gt;

&lt;p&gt;Objective-C and C++ were created with very different purposes.  The former was an experiment in combining the dynamism of Smalltalk on top of the C language.  C++, on the other hand, was built to add the object oriented features of Simula to C, but without suffering from Simula’s performance problems.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;PC Week&lt;/em&gt; summed up this difference nicely in their 3 Nov 1997 edition:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;Objective-C is the result of adding object facilities to C with the goal of making programmers more productive. The result differs greatly from C++, which adds objects to C without making computers less efficient: quite a different goal.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I’ve found this to be the case in my own use of the language.  I’ve learned several languages over the past decade, and Objective-C is the only language I’ve actually enjoyed using.  Of course, each language  has its flaws (including Objective-C), but Objective-C gives me the organization of an object-oriented language like C++ or Java, the power of a dynamic and flexible runtime like a scripting language, all built on top of the power of C.  There are tradeoffs to this (Objective-C tends to be slightly slower than C++), but for me, the benefits far outweigh the costs.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/3022015652</link><guid>http://funwithobjc.tumblr.com/post/3022015652</guid><pubDate>Sun, 30 Jan 2011 17:08:00 -0800</pubDate></item><item><title>I've really been enjoying your posts, but you don't have any personal information on your site, as far as I could find. Who are you?</title><description>&lt;p&gt;No one of consequence…&lt;/p&gt;

&lt;p&gt;My name is Dave DeLong.  I’m a frameworks engineer at Apple, where I work on the UIKit framework.  I spend my spare time with my family and playing with the Objective-C runtime.  I also believe that the existence of chocolate and peanut butter are proof that there is a God, and that He loves us.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/2922325546</link><guid>http://funwithobjc.tumblr.com/post/2922325546</guid><pubDate>Tue, 25 Jan 2011 00:39:14 -0800</pubDate></item><item><title>Using custom functions with NSExpression</title><description>&lt;p&gt;There are a bunch of built-in functions in the &lt;code&gt;NSExpression&lt;/code&gt; class that allow you to do some pretty neat stuff.  &lt;a href="http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSExpression_Class/Reference/NSExpression.html#//apple_ref/doc/uid/TP30001190-CJBDJCJE"&gt;They are&lt;/a&gt;: &lt;code&gt;average:&lt;/code&gt;, &lt;code&gt;sum:&lt;/code&gt;, &lt;code&gt;count:&lt;/code&gt;, &lt;code&gt;min:&lt;/code&gt;, &lt;code&gt;max:&lt;/code&gt;, &lt;code&gt;median:&lt;/code&gt;, &lt;code&gt;mode:&lt;/code&gt;, &lt;code&gt;stddev:&lt;/code&gt;, &lt;code&gt;add:to:&lt;/code&gt;, &lt;code&gt;from:subtract:&lt;/code&gt;, &lt;code&gt;multiply:by:&lt;/code&gt;, &lt;code&gt;divide:by:&lt;/code&gt;, &lt;code&gt;modulus:by:&lt;/code&gt;, &lt;code&gt;sqrt:&lt;/code&gt;, &lt;code&gt;log:&lt;/code&gt;, &lt;code&gt;ln:&lt;/code&gt;, &lt;code&gt;raise:toPower:&lt;/code&gt;, &lt;code&gt;exp:&lt;/code&gt;, &lt;code&gt;ceiling:&lt;/code&gt;, &lt;code&gt;abs:&lt;/code&gt;, &lt;code&gt;trunc:&lt;/code&gt;, &lt;code&gt;random&lt;/code&gt;, &lt;code&gt;random:&lt;/code&gt;, &lt;code&gt;now&lt;/code&gt;, &lt;code&gt;floor:&lt;/code&gt;, &lt;code&gt;uppercase:&lt;/code&gt;, &lt;code&gt;lowercase:&lt;/code&gt;, &lt;code&gt;bitwiseAnd:with:&lt;/code&gt;, &lt;code&gt;bitwiseOr:with:&lt;/code&gt;, &lt;code&gt;bitwiseXor:with:&lt;/code&gt;, &lt;code&gt;leftshift:by:&lt;/code&gt;, &lt;code&gt;rightshift:by:&lt;/code&gt;, &lt;code&gt;onesComplement:&lt;/code&gt;, and &lt;code&gt;noindex:&lt;/code&gt;.  That&amp;#8217;s a lot of functions!  You have your arithmetic functions, some multi-parameter functions, some bitwise functions, and a few miscellaneous ones thrown in for good measure.&lt;/p&gt;

&lt;p&gt;But&amp;#8230; what if you want to find the factorial of a number?  Or use any sort of trigonometric function?  Or say you wanted to do something much more complex?  Are you out of luck?&lt;/p&gt;

&lt;p&gt;Fortunately, no.  There &lt;em&gt;is&lt;/em&gt; a way to do custom functions in &lt;code&gt;NSExpression&lt;/code&gt;, with the downside that the syntax is a little bit more complex than your standard functions.&lt;/p&gt;

&lt;p&gt;The built-in functions can be written as if they were actual functions:  &lt;code&gt;now()&lt;/code&gt;, &lt;code&gt;sqrt(42)&lt;/code&gt;, &lt;code&gt;6 * 9&lt;/code&gt;, etc.  Unfortunately, we cannot do that with our custom functions.  Oh well.  Let&amp;#8217;s get over that and move on.&lt;/p&gt;

&lt;h3&gt;The Syntax&lt;/h3&gt;

&lt;p&gt;The syntax for all functions is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FUNCTION(operand, 'function', arguments, ...)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In a nutshell, the result of the function is the result of invoking the &lt;code&gt;function&lt;/code&gt; method on &lt;code&gt;operand&lt;/code&gt;, while passing in the &lt;code&gt;arguments&lt;/code&gt; as parameters to the method.&lt;/p&gt;

&lt;p&gt;If we dive into one of the &lt;code&gt;NSExpressions&lt;/code&gt; produced by a standard function, we learn some interesting things.  Let&amp;#8217;s example the function &amp;#8220;&lt;code&gt;6*9&lt;/code&gt;&amp;#8221;.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSExpression * e = [(NSComparisonPredicate *)[NSPredicate predicateWithFormat:@"6*9 = 1"] leftExpression];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;-operand&lt;/code&gt; of this expression is another &lt;code&gt;NSExpression&lt;/code&gt;.  In the case of these built-in functions, it turns out that it&amp;#8217;s a constant value expression encapsulating a &lt;code&gt;Class&lt;/code&gt; object of type &lt;code&gt;_NSPredicateUtilities&lt;/code&gt;.  Some runtime introspection on this object shows that it has a whole bunch of class methods that correspond to all of the built-in functions, along with one that&amp;#8217;s &lt;em&gt;not&lt;/em&gt; listed in the documentation: &lt;code&gt;castObject:toType:&lt;/code&gt;.  We previously discussed using this function with &lt;a href="http://tumblr.com/xqorqjfrz"&gt;advanced date predicates&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;operand&lt;/code&gt; is an &lt;code&gt;NSExpression&lt;/code&gt; (as opposed to an &lt;code&gt;id&lt;/code&gt;), because the object receiving the method could be the result of another expression.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;function&lt;/code&gt; in our multiplication expression is &amp;#8220;&lt;code&gt;multiply:by:&lt;/code&gt;&amp;#8221;, as we would expect.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;arguments&lt;/code&gt; to our multiplication is an &lt;code&gt;NSArray&lt;/code&gt; of &lt;code&gt;NSExpression&lt;/code&gt; objects.  They are expressions for the same reason that the &lt;code&gt;operand&lt;/code&gt; is an &lt;code&gt;NSExpression&lt;/code&gt;.  In our example, we have two expressions, both representing &lt;code&gt;NSNumbers&lt;/code&gt; as constant values.&lt;/p&gt;

&lt;h3&gt;Custom Functions&lt;/h3&gt;

&lt;p&gt;Now that we understand the syntax behind &lt;code&gt;FUNCTION()&lt;/code&gt;, it should be fairly obvious how to go about making our own functions.  Here&amp;#8217;s what we need:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;An object on which to operate.&lt;/li&gt;
&lt;li&gt;A method to invoke&lt;/li&gt;
&lt;li&gt;Parameters to pass in (optional)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;So let&amp;#8217;s say we want to add a factorial function.  We have two options on how to approach this:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Make our factorial method receive the number as a parameter&lt;/li&gt;
&lt;li&gt;Make our factorial method operate on a number directly&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;I personally prefer the latter approach, since the syntax is slightly less complicated.  Here&amp;#8217;s what we would do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@interface NSNumber (FactorialExpression)

- (NSNumber *) factorial;

@end

@implementation NSNumber (FactorialExpression)

- (NSNumber *) factorial {
  double baseValue = [self doubleValue];
  double result = tgamma(baseValue+1);
  return [NSNumber numberWithDouble:result];
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;(This method uses the &lt;a href="http://en.wikipedia.org/wiki/Gamma_function"&gt;Gamma Function&lt;/a&gt;, which allows for computing the factorial of non-integral numbers)&lt;/p&gt;

&lt;p&gt;Then in our format string, we would express it like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;FUNCTION(4.2, 'factorial')
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we evaluate that expression, we get &lt;code&gt;32.57809605033135&lt;/code&gt;, as we were hoping!  The key thing here is realizing that &lt;code&gt;4.2&lt;/code&gt; will be boxed in an &lt;code&gt;NSNumber&lt;/code&gt;, which means that the &lt;code&gt;factorial&lt;/code&gt; method will be invoked on &lt;code&gt;NSNumber&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Venturing Toward the Absurd&lt;/h3&gt;

&lt;p&gt;OK, we&amp;#8217;ve got basic functions down.  What about functions that take arguments?  For this next example, we&amp;#8217;ll take a look at a custom function being used in &lt;a href="http://stackkit.com"&gt;StackKit&lt;/a&gt;, a framework for accessing the &lt;a href="http://stackapps.com"&gt;Stack Overflow API&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;At the heart of StackKit is a URL generation system that will turn a combination of an &lt;code&gt;NSPredicate&lt;/code&gt;, an &lt;code&gt;NSSortDescriptor&lt;/code&gt;, and a &lt;code&gt;Class&lt;/code&gt; into an HTTP GET request that can be used to retrieve data from one of the Stack Exchange sites (like &lt;a href="http://stackoverflow.com"&gt;http://stackoverflow.com&lt;/a&gt;).  Due to the limited nature of the API, only certain predicates and sort descriptors are allowed, and only in very specific combinations.&lt;/p&gt;

&lt;p&gt;One of the parts of &amp;#8220;validating&amp;#8221; an &lt;code&gt;NSPredicate&lt;/code&gt; is to verify that it is only using allowed keyPaths, and that these keyPaths are being compared with specific operators.  Each of the &amp;#8220;RequestBuilder&amp;#8221; classes vends an &lt;code&gt;NSDictionary&lt;/code&gt; called the &lt;code&gt;recognizedPredicateKeyPaths&lt;/code&gt;.  This dictionary is a map of keyPaths (as the key) to an &lt;code&gt;NSArray&lt;/code&gt; of &lt;code&gt;NSNumber&lt;/code&gt; objects.  The &lt;code&gt;NSNumbers&lt;/code&gt; box an &lt;a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSComparisonPredicate_Class/Reference/NSComparisonPredicate.html#//apple_ref/doc/uid/TP30001189-BBCHHCAD"&gt;&lt;code&gt;NSPredicateOperatorType&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Since each builder recognizes different keyPaths and different operators, I had to get a little creative.  Here&amp;#8217;s what the code looks like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;p = [NSPredicate predicateWithFormat:@"FUNCTION(%@, 'sk_matchesRecognizedKeyPathsAndOperators:', SELF.recognizedPredicateKeyPaths) == YES", predicateToValidate];
[builders filterUsingPredicate:p];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In this case, &lt;code&gt;predicateToValidate&lt;/code&gt; is the user-supplied &lt;code&gt;NSPredicate&lt;/code&gt;.  I&amp;#8217;m going to be passing this predicate in as the operand to my FUNCTION.  The method that will be invoked on it is &lt;code&gt;@selector(sk_matchesRecognizedKeyPathsAndOperators:)&lt;/code&gt;, which is conveniently provided via an &lt;code&gt;NSPredicate&lt;/code&gt; category.  Finally, the argument to this function is the dictionary of the current request builder.  If the &lt;code&gt;sk_matchesRecognizedKeyPathsAndOperators:&lt;/code&gt; method returns &lt;code&gt;YES&lt;/code&gt;, then we&amp;#8217;ve passed this particular step of the validation.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/davedelong/StackKit/blob/10f24c24d457363cf1480b98084da54568fba943/Classes/NSPredicate%2BSKAdditions.m#L261"&gt;The code for the &lt;code&gt;NSPredicate&lt;/code&gt; method is fairly simple&lt;/a&gt;; it simply iterates through all of the keys in the &lt;code&gt;NSDictionary&lt;/code&gt;, then extracts the subpredicates of the &amp;#8220;&lt;code&gt;predicateToValidate&lt;/code&gt;&amp;#8221; for each key.  Of these subpredicates, if there&amp;#8217;s one that&amp;#8217;s using an operator that&amp;#8217;s not recognized, then we abort and return &lt;code&gt;NO&lt;/code&gt;.  Otherwise we&amp;#8217;ll get to the end, find that all of our subpredicates are using allowed operators, and return &lt;code&gt;YES&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The result of those two lines of code is that the &lt;code&gt;builders&lt;/code&gt; array will be filtered to only contain the builders that allow the left keyPaths and operators that are specified in the user-provided predicate.&lt;/p&gt;

&lt;p&gt;(For more fun, exciting, and absurd uses of &lt;code&gt;NSPredicate&lt;/code&gt;, check out &lt;a href="https://github.com/davedelong/StackKit/blob/master/Classes/SKRequestBuilder.m#L61"&gt;&lt;code&gt;SKRequestBuilder.m&lt;/code&gt;&lt;/a&gt;.)&lt;/p&gt;

&lt;h3&gt;A Caution&lt;/h3&gt;

&lt;p&gt;One of the things to be wary of when using custom functions is that &lt;em&gt;&lt;strong&gt;all&lt;/strong&gt;&lt;/em&gt; of the parameters to the method must be objects, and the return value of the method must also be an object!  This means that you cannot do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[NSPredicate predicateWithFormat:@"FUNCTION('a', 'isEqual:', 'a') == YES"];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you try to evaluate that predicate, it will crash.  &lt;code&gt;NSExpression&lt;/code&gt; is attempting to cast the result of the &lt;code&gt;isEqual:&lt;/code&gt; method as an object.  However, &lt;code&gt;(id)1&lt;/code&gt; is not an object recognizable by Objective-C, no matter how you cast it.&lt;/p&gt;

&lt;p&gt;Instead, if you needed to do this, you&amp;#8217;d add a method that simply boxed the result in the appropriate &lt;code&gt;NSValue&lt;/code&gt; object and use that method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@implementation NSString (CustomFunction)

- (NSNumber *) dd_isEqual:(id)other {
  return [NSNumber numberWithBool:[self isEqual:other]];
}

@end

...

FUNCTION('a', 'dd_isEqual:', 'a')
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will work just fine.&lt;/p&gt;

&lt;h3&gt;Wrap Up&lt;/h3&gt;

&lt;p&gt;Custom functions in &lt;code&gt;NSExpression&lt;/code&gt; are pretty neat.  You don&amp;#8217;t find yourself using them very often, but when you need them, they can be extremely handy!&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/2922267976</link><guid>http://funwithobjc.tumblr.com/post/2922267976</guid><pubDate>Tue, 25 Jan 2011 00:28:00 -0800</pubDate><category>nsexpression</category></item><item><title>What the heck is SUBQUERY?</title><description>&lt;p&gt;One of the lesser known bits of &lt;code&gt;NSPredicate&lt;/code&gt; is the &lt;code&gt;SUBQUERY()&lt;/code&gt; function.  The &lt;a href="http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSExpression_Class/Reference/NSExpression.html#//apple_ref/doc/uid/TP30001190-SW22"&gt;documentation for a subquery expression&lt;/a&gt; explains a little bit about what&amp;#8217;s going on, but it takes a while to understand when it&amp;#8217;s really useful.&lt;/p&gt;

&lt;p&gt;Let&amp;#8217;s break it down.&lt;/p&gt;

&lt;h1&gt;The Syntax&lt;/h1&gt;

&lt;p&gt;A subquery expression takes 3 arguments:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;A collection&lt;/li&gt;
&lt;li&gt;A variable name&lt;/li&gt;
&lt;li&gt;A predicate&lt;/li&gt;
&lt;/ol&gt;&lt;h3&gt;The Collection&lt;/h3&gt;

&lt;p&gt;The collection can be one of the two standard Cocoa collection:  &lt;code&gt;NSArray&lt;/code&gt; and &lt;code&gt;NSSet&lt;/code&gt; (or some subclass of them).  This collection can be hard-coded in, or it can be the result of another expression (like a keyPath expression or the like).  A hard-coded collection would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SUBQUERY(%@, ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;A keyPath expression would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SUBQUERY(contents, ...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;With the stipulation that &lt;code&gt;[self contents]&lt;/code&gt; (or &lt;code&gt;self.contents&lt;/code&gt; if you prefer) must return an &lt;code&gt;NSArray&lt;/code&gt; or &lt;code&gt;NSSet&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;The Variable&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;SUBQUERY&lt;/code&gt; is going to iterate over the collection, gathering certain objects.  We need a way to represent what each item in the collection is, and for that we use the variable.&lt;/p&gt;

&lt;p&gt;Variables in an &lt;code&gt;NSExpression&lt;/code&gt; (or &lt;code&gt;NSPredicate&lt;/code&gt; format string) take the form &lt;code&gt;$identifier&lt;/code&gt;, where &lt;code&gt;identifier&lt;/code&gt; is a valid C-style identifier.  Most examples of &lt;code&gt;SUBQUERY&lt;/code&gt; generally use &lt;code&gt;$x&lt;/code&gt; as the variable.  It&amp;#8217;s short and to-the-point.&lt;/p&gt;

&lt;p&gt;It&amp;#8217;s the second argument in the expression:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SUBQUERY(contents, $x, ...
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;The Predicate&lt;/h3&gt;

&lt;p&gt;A predicate, as we know, is a statement that evaluates to true or false.  In the case of the subquery, the predicate will be evaluated for each object (represented by the variable) in the collection.  If the predicate returns true, then that object will be included as part of the resulting collection.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SUBQUERY(contents, $x, $x.property = 'foo' and $x.number = 42)
&lt;/code&gt;&lt;/pre&gt;

&lt;h3&gt;TL;DR&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;SUBQUERY()&lt;/code&gt; expression is the functional equivalent of doing this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSPredicate * p = [NSPredicate predicateWithFormat:@"property = 'foo' and number = 4"];
NSArray * results = [[self contents] filteredArrayUsingPredicate:p];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If this were expressed as a subquery in a predicate, it would be:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSPredicate * p = [NSPredicate predicateWithFormat:@"SUBQUERY(contents, $x, $x.property = 'foo' and $x.number = 42) ..."];  
//with some operation to use the resulting collection in a comparison or something
&lt;/code&gt;&lt;/pre&gt;

&lt;h1&gt;So what?&lt;/h1&gt;

&lt;p&gt;Now that we get what the various bits of a subquery expression are, let&amp;#8217;s ask the real question: when is this ever useful?&lt;/p&gt;

&lt;p&gt;To be honest, the answer to this is &amp;#8220;not often&amp;#8221;.  However, when you need it, it&amp;#8217;s incredibly useful.&lt;/p&gt;

&lt;h3&gt;Rule of thumb&lt;/h3&gt;

&lt;p&gt;The general rule of thumb on when you should consider using &lt;code&gt;SUBQUERY&lt;/code&gt; is this:&lt;/p&gt;

&lt;p&gt;If you have a collection (&lt;code&gt;A&lt;/code&gt;) of objects, and each object has a collection (&lt;code&gt;B&lt;/code&gt;) of other objects, and you&amp;#8217;re trying to filter &lt;code&gt;A&lt;/code&gt; based on some varying attributes (at least 2) of the objects in &lt;code&gt;B&lt;/code&gt;, then you should probably be using &lt;code&gt;SUBQUERY&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;Example&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s say you have a bunch of &lt;code&gt;Project&lt;/code&gt; objects, and each &lt;code&gt;Project&lt;/code&gt; has a bunch of &lt;code&gt;ToDo&lt;/code&gt; items.  A &lt;code&gt;ToDo&lt;/code&gt; item has a &lt;code&gt;completionDate&lt;/code&gt; (an &lt;code&gt;NSDate&lt;/code&gt;) and a &lt;code&gt;user&lt;/code&gt; (a name).  You want to find all projects that have a todo item that was completed by Joey (so &lt;code&gt;completionDate&lt;/code&gt; is not &lt;code&gt;nil&lt;/code&gt; and &lt;code&gt;user&lt;/code&gt; is &amp;#8220;Joey&amp;#8221;).  We&amp;#8217;re going to display these in a &amp;#8220;Joey&amp;#8217;s Recent Projects&amp;#8221; group (or something).&lt;/p&gt;

&lt;p&gt;Our first reaction might be a predicate that uses &lt;code&gt;ANY&lt;/code&gt; in there, like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ANY todos.completionDate != nil AND ANY todos.user == joey
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately, that would give us projects that have at least one completed &lt;code&gt;ToDo&lt;/code&gt; and that has a &lt;code&gt;ToDo&lt;/code&gt; whose &lt;code&gt;user&lt;/code&gt; is Joey.  However, they don&amp;#8217;t have to be the same &lt;code&gt;ToDo&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The proper predicate is:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;SUBQUERY(todos, $todo, $todo.completionDate != nil AND $todo.user = 'Joey').@count &amp;gt; 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This predicate will be evaluated against each &lt;code&gt;Project&lt;/code&gt;.  First, we&amp;#8217;ll get the collection of &lt;code&gt;ToDo&lt;/code&gt; objects by evaluating the &lt;code&gt;todo&lt;/code&gt; keyPath on the &lt;code&gt;Project&lt;/code&gt;.  Then for each item (&lt;code&gt;$todo&lt;/code&gt;) in the array of &lt;code&gt;ToDo&lt;/code&gt; objects, we&amp;#8217;re going to check and see if that object&amp;#8217;s &lt;code&gt;completionDate&lt;/code&gt; is non-nil and if that object&amp;#8217;s user is &lt;code&gt;"Joey"&lt;/code&gt;.  If that&amp;#8217;s true, then it&amp;#8217;ll be added to the resulting collection.&lt;/p&gt;

&lt;p&gt;When the &lt;code&gt;SUBQUERY&lt;/code&gt; completes, we&amp;#8217;ll have an array of &lt;code&gt;ToDo&lt;/code&gt; items that were completed by Joey.  At this point, we retrieve the number of items in that collection (via the &lt;code&gt;@count&lt;/code&gt; keyPath) and see if it&amp;#8217;s greater than 0.  If it is, then the corresponding &lt;code&gt;Project&lt;/code&gt; will be added to the final array.  In this manner, we can retrieve all Projects that have ToDos completed by Joey.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/2726166818</link><guid>http://funwithobjc.tumblr.com/post/2726166818</guid><pubDate>Wed, 12 Jan 2011 22:38:00 -0800</pubDate></item><item><title>Creating an advanced NSPredicateEditorRowTemplate</title><description>&lt;p&gt;In a recent post I covered &lt;a href="http://tumblr.com/xqor81lfy"&gt;how to make a simple &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt;&lt;/a&gt;.  In this post we&amp;#8217;re going to go a bit deeper.&lt;/p&gt;

&lt;h2&gt;The Setup&lt;/h2&gt;

&lt;p&gt;In our last example, we did some simple date comparisons, where we were comparing an &lt;code&gt;NSTimeInterval&lt;/code&gt; against a property that represented a duration.  For example, if we had an array of &lt;code&gt;Song&lt;/code&gt; objects, then we could use that row template to construct a predicate to find all songs that were longer than 5 minutes (&lt;code&gt;duration &amp;gt; 300&lt;/code&gt;).  But what if our objects don&amp;#8217;t have a duration property?  What if they have a date property, such as &lt;code&gt;the date this song was added&lt;/code&gt;?  Well, we can use the built-in initializers of &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt; to create a template where the right expression type is &lt;code&gt;NSDateAttributeType&lt;/code&gt;.  This is all well and good, but it has a fundamental flaw:  It can only compare against static dates.&lt;/p&gt;

&lt;p&gt;In other words, I can easily create a row template for predicates of the form &lt;code&gt;&amp;lt;a date&amp;gt; &amp;lt;is, is not, is before, is on or before, is after, is on or after&amp;gt; &amp;lt;a specific date&amp;gt;&lt;/code&gt;.  But what if I want to do something like &lt;code&gt;&amp;lt;a date&amp;gt; &amp;lt;is in the last, is in the next&amp;gt; &amp;lt;user-entered number&amp;gt; &amp;lt;seconds, minutes, hours, days, weeks&amp;gt;&lt;/code&gt;?  Is there a way to do relative date comparison?  The answer is &amp;#8220;yes&amp;#8221;, but this is going to take a lot of explanation.  So buckle up, and let&amp;#8217;s dive right in!&lt;/p&gt;

&lt;h2&gt;The Problems&lt;/h2&gt;

&lt;p&gt;There are two major problems to overcome when doing relative date comparison and integrating that with &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;p&gt;&lt;code&gt;NSPredicateEditor&lt;/code&gt; compacts left expressions into a unique list.  Where a left expression supports multiple operators, those are also uniqued. In other words, you can&amp;#8217;t do both &lt;code&gt;myKeyPath = &amp;lt;a value form a textfield&amp;gt;&lt;/code&gt; and &lt;code&gt;myKeyPath = &amp;lt;a value from a popup&amp;gt;&lt;/code&gt; in the same &lt;code&gt;NSPredicateEditor&lt;/code&gt;.  It doesn&amp;#8217;t matter if these are defined in different row templates. &lt;code&gt;NSPredicateEditor&lt;/code&gt; will still find both of them, and won&amp;#8217;t know what to display when the user chooses &lt;code&gt;myKeyPath&lt;/code&gt; from the first popup and &lt;code&gt;=&lt;/code&gt; from the second popup.  What should it display?  A textfield?  A popupmenu?  We care about this because if we want to support both &lt;code&gt;myDate &amp;lt;is after&amp;gt; &amp;lt;a specific date&amp;gt;&lt;/code&gt; and &lt;code&gt;myDate &amp;lt;is in the last&amp;gt; &amp;lt;number&amp;gt; &amp;lt;time unit&amp;gt;&lt;/code&gt;, these both boil down to the same thing (after doing dynamic date resolution): find if one date is after another date.  In other words, the same left expression, the same operator, but different right expressions.  &lt;code&gt;NSPredicateEditor&lt;/code&gt; doesn&amp;#8217;t support this.  We need to find a way around this.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;NSPredicate&lt;/code&gt; doesn&amp;#8217;t have any obvious date addition or date subtraction features.  We need to figure out how to add and subtract arbitrary time intervals from arbitrary dates.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;&lt;h2&gt;The Solutions&lt;/h2&gt;

&lt;p&gt;While these may seem like road-blocker problems, they&amp;#8217;re really not too bad.&lt;/p&gt;

&lt;h3&gt;Solving the operator problem&lt;/h3&gt;

&lt;p&gt;The key to tricking &lt;code&gt;NSPredicateEditor&lt;/code&gt; into showing different right expressions for two operators that are fundamentally the same is to not use the same operator.  These are the operators that &lt;code&gt;NSPredicateEditor&lt;/code&gt; recognizes:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;typedef enum {
   NSLessThanPredicateOperatorType = 0,
   NSLessThanOrEqualToPredicateOperatorType,
   NSGreaterThanPredicateOperatorType,
   NSGreaterThanOrEqualToPredicateOperatorType,
   NSEqualToPredicateOperatorType,
   NSNotEqualToPredicateOperatorType,
   NSMatchesPredicateOperatorType,
   NSLikePredicateOperatorType,
   NSBeginsWithPredicateOperatorType,
   NSEndsWithPredicateOperatorType,
   NSInPredicateOperatorType,
   NSCustomSelectorPredicateOperatorType,
   NSContainsPredicateOperatorType,
   NSBetweenPredicateOperatorType
} NSPredicateOperatorType;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You&amp;#8217;ll notice that only six of 14 operators are for numeric comparisons (&lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;lt;=&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;gt;=&lt;/code&gt;, &lt;code&gt;=&lt;/code&gt;, &lt;code&gt;!=&lt;/code&gt;).  The rest are for string comparisons.    This means we have 7 or 8 operators that are sitting around unused when we&amp;#8217;re doing a numeric comparison (and date comparisons are really numeric comparisons).&lt;/p&gt;

&lt;p&gt;The other key to tricking &lt;code&gt;NSPredicateEditor&lt;/code&gt; into showing different right expressions is to realize that &lt;code&gt;NSPredicateEditor&lt;/code&gt; is just a UI.  It doesn&amp;#8217;t care what the actual underlying &lt;code&gt;NSPredicate&lt;/code&gt; is.  It&amp;#8217;s just going to show whatever it&amp;#8217;s given, &lt;em&gt;even if that is different from the actual &lt;code&gt;NSPredicate&lt;/code&gt;&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;So the solution:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#define NSInTheLastPredicateOperatorType NSMatchesPredicateOperatorType
#define NSInTheNextPredicateOperatorType NSLikePredicateOperatorType
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s it.  Any time we want to show an &amp;#8220;in the last&amp;#8221;-style right expression, we&amp;#8217;re going to tell the editor &amp;#8220;this is the &amp;#8216;matches&amp;#8217;&amp;#8221; operator.  Then we&amp;#8217;re just going to do a bit of handling in code to not actually use the &lt;code&gt;matches&lt;/code&gt; operator, but the proper comparator instead.  Simple!&lt;/p&gt;

&lt;h3&gt;Solving the relative date problem&lt;/h3&gt;

&lt;p&gt;Have you ever looked at how dates are represented in predicates?  It&amp;#8217;s quite interesting:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSDate * d = [NSDate date];
NSLog(@"%@", [NSPredicate predicateWithFormat:@"%@ != 0", d]);
//logs "CAST(312333057.230785, "NSDate") != 0"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Well now, &lt;em&gt;that&amp;#8217;s&lt;/em&gt; curious.  We&amp;#8217;re taking some number and &amp;#8220;casting&amp;#8221; it as an &lt;code&gt;NSDate&lt;/code&gt;.  But what&amp;#8217;s that number?  Let&amp;#8217;s do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSLog(@"%f", [d timeIntervalSinceReferenceDate]);
//logs "312333057.230785"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So this number is a time interval!  This is very convenient.  But what about all this casting?  If we capture the left expression of this predicate, we will find that it&amp;#8217;s an &lt;code&gt;NSExpression&lt;/code&gt; of type &lt;code&gt;NSFunctionExpressionType&lt;/code&gt;, and that the &lt;code&gt;-function&lt;/code&gt; of this expression is &lt;code&gt;@"castObject:toType:"&lt;/code&gt;.  Further introspection reveals that the &lt;code&gt;-arguments&lt;/code&gt; to this function are two &lt;code&gt;NSExpressions&lt;/code&gt;:  The first is a constant value expression holding an &lt;code&gt;NSNumber&lt;/code&gt;, whose &lt;code&gt;-doubleValue&lt;/code&gt; is &lt;code&gt;312333057.230785&lt;/code&gt;, and the second is a constant value expression holding the string &lt;code&gt;@"NSDate"&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is very important, because we learn 3 major things:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;There is an undocumented function for &lt;code&gt;NSExpression&lt;/code&gt;:  &lt;code&gt;castObject:toType:&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;This function wants a number as its first argument&lt;/li&gt;
&lt;li&gt;This function wants a string (that represents a class) as its second argument.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Armed with this information, we can surmise:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;We can create predicates that have the string &lt;code&gt;CAST()&lt;/code&gt; in them.  We don&amp;#8217;t have to rely on &lt;code&gt;predicateWithFormat:&lt;/code&gt; to insert that for us.&lt;/li&gt;
&lt;li&gt;Any number, or any function that results in a number, can be used as the first parameter to a &lt;code&gt;CAST()&lt;/code&gt; function and be cast to an &lt;code&gt;NSDate&lt;/code&gt;.  That number represents a time interval since the first instant of &lt;code&gt;1 January 2001, GMT&lt;/code&gt; (the reference date).&lt;/li&gt;
&lt;li&gt;We can cast objects to other kinds of classes&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Let&amp;#8217;s test each one of these things:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSPredicate * p = [NSPredicate predicateWithFormat:@"%@ &amp;gt; CAST(0, 'NSDate')", [NSDate date]];
NSLog(@"%d", [p evaluateWithObject:nil]);  //logs "1".  right now is after our reference date!

p = [NSPredicate predicateWithFormat:@"%@ &amp;gt; CAST(1+2+3+4+5+6, 'NSDate')", [NSDate date]];
NSLog(@"%d", [p evaluateWithObject:nil]);  //logs "1".  right now is after 21 seconds after the reference date!

p = [NSPredicate predicateWithFormat:@"CAST(%@, 'NSNumber') &amp;gt; 0", [NSDate date]];
NSLog(@"%d", [p evaluateWithObject:nil]);  //logs "1". We can cast dates to their numerical equivalent!
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So all three of our assumptions appear to be correct!  The last one is the most interesting, however.  If we pull out the &lt;code&gt;leftExpression&lt;/code&gt; of the predicate and evaluate it, we get &lt;code&gt;312333057.230785&lt;/code&gt;.  In other words, casting a date to a number simply converts it to its reference date time interval!  Since we could cast a number to a date, it makes perfect sense that we can cast a date to a number.&lt;/p&gt;

&lt;p&gt;The last trick is &amp;#8220;how do we get the current date without having to substitute it in every time?&amp;#8221;.  Fortunately, there&amp;#8217;s a very simple answer:  &lt;code&gt;now()&lt;/code&gt;.  &lt;code&gt;now()&lt;/code&gt; is one of the built-in functions supported by &lt;code&gt;NSExpression&lt;/code&gt;, and it (conveniently enough) returns an &lt;code&gt;NSDate&lt;/code&gt; representing the current date and time.&lt;/p&gt;

&lt;p&gt;Now that we know this, we can construct relative date predicates!  So for example, let&amp;#8217;s do &amp;#8220;someDate is in the last 30 days&amp;#8221;.  If a date is in the last 30 days, that means that &lt;code&gt;someDate&lt;/code&gt; is after &lt;code&gt;now - 30 days&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[NSPrediate predicateWithFormat:@"someDate &amp;gt; CAST(CAST(now(), 'NSNumber') - %d, 'NSDate')", (30*86400)];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Working from the inside-out, we have:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;now()&lt;/code&gt; - retrieve the current &lt;code&gt;NSDate&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CAST(now(), 'NSNumber')&lt;/code&gt; - convert the current date into an &lt;code&gt;NSNumber&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CAST(now(), 'NSNumber') - %d&lt;/code&gt; - subtract a time interval from the current timestamp.  This difference must be in seconds. &lt;code&gt;30*86400&lt;/code&gt; is 30 days in seconds (there are 86,400 seconds in a day)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;CAST(CAST(now(), 'NSNumber') - %d, 'NSDate')&lt;/code&gt; - once we&amp;#8217;ve done our subtraction, cast the time interval back to an &lt;code&gt;NSDate&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;At this point, we can compare it against our target date.  We could&amp;#8217;ve done the date subtraction on the value returned by the left expression, but there are some circumstances where that&amp;#8217;s not a good idea (primarily when integrating with CoreData), so we&amp;#8217;ll keep it in the right.&lt;/p&gt;

&lt;p&gt;Voilà!  Date subtraction in an &lt;code&gt;NSPredicate&lt;/code&gt;!  Doing something like &amp;#8220;&lt;code&gt;&amp;lt;some date&amp;gt; is during &amp;lt;this week, this month, this year&amp;gt;&lt;/code&gt;&amp;#8221; would be slightly more complex (it would involve a &lt;code&gt;BETWEEN&lt;/code&gt; comparison [or something functionally identical]), but still do-able.  Even more fun would be a predicate of the form &amp;#8220;&lt;code&gt;&amp;lt;some date&amp;gt; is during the &amp;lt;day, week, month, year&amp;gt; of &amp;lt;another date&amp;gt;&lt;/code&gt;&amp;#8221;.  Also very difficult, but again not impossible.  Maybe we&amp;#8217;ll do those in another post.  Anyway&amp;#8230;&lt;/p&gt;

&lt;h2&gt;The Row Template&lt;/h2&gt;

&lt;p&gt;Our row template is going to be very similar to the template in my earlier post, because (again) we&amp;#8217;re doing &lt;code&gt;NSTimeInterval&lt;/code&gt; manipulations.  Let&amp;#8217;s get started:&lt;/p&gt;

&lt;h3&gt;The Interface&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;@interface DDRelativeDateRowTemplate : NSPredicateEditorRowTemplate {
    NSPopUpButton * unitPopUpButton;
}

- (id) initWithLeftExpressions:(NSArray *)leftExpressions;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nothing new to see here.&lt;/p&gt;

&lt;h3&gt;The Implementation&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;#define NSInTheLastPredicateOperatorType NSMatchesPredicateOperatorType
#define NSInTheNextPredicateOperatorType NSLikePredicateOperatorType
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some &lt;code&gt;#defines&lt;/code&gt; to make things a bit more readable in our code&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@implementation DDRelativeDateRowTemplate

- (id) initWithLeftExpressions:(NSArray *)leftExpressions {
    NSAttributeType rightType = NSDoubleAttributeType; //NSTimeInterval is a typedef'd double
    NSComparisonPredicateModifier modifier = NSDirectPredicateModifier; //don't need "ANY" or "ALL"
    NSArray * operators = [NSArray arrayWithObjects:
                           [NSNumber numberWithUnsignedInteger:NSInTheLastPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSInTheNextPredicateOperatorType],
                           nil];
    NSUInteger options = 0;
    return [super initWithLeftExpressions:leftExpressions
             rightExpressionAttributeType:rightType
                                 modifier:modifier
                                operators:operators
                                  options:options];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our &lt;code&gt;init&lt;/code&gt; method is almost identical to the &lt;code&gt;init&lt;/code&gt; method in our previous template, with the exception that this time we&amp;#8217;re only supporting 2 operators.  Notice that we&amp;#8217;re telling the predicate editor that these are the &amp;#8220;matches&amp;#8221; and &amp;#8220;like&amp;#8221; operators.  Again, this is only to get around problem #1 (see above).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static NSString * unitNames[] = {@"seconds", @"minutes", @"hours", @"days", @"weeks"};
static NSInteger unitIntervals[] = {1, 60, 3600, 86400, 604800};
#define numberOfUnits() (sizeof(unitNames)/sizeof(unitNames[0]))

- (NSPopUpButton *) unitPopUpButton {
    if (unitPopUpButton == nil) {
        unitPopUpButton = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];

        NSMenu * unitMenu = [unitPopUpButton menu];
        for (int i = 0; i &amp;lt; numberOfUnits(); ++i) {
            [unitMenu addItemWithTitle:unitNames[i] action:NULL keyEquivalent:@""];
        }
    }
    return unitPopUpButton;
}

- (void) dealloc {
    [unitPopUpButton release];
    [super dealloc];
}

- (void) getBase:(NSTimeInterval *)base unit:(NSInteger *)unit fromTimeInterval:(NSTimeInterval)timeInterval {
    if (base == nil || unit == nil) {
        [NSException raise:NSInvalidArgumentException format:@"base and unit cannot be nil"];
    }

    for (NSInteger unitIndex = numberOfUnits() - 1; unitIndex &amp;gt;= 0; unitIndex--) {
        if (timeInterval &amp;gt;= unitIntervals[unitIndex]) {
            *base = timeInterval / unitIntervals[unitIndex];
            *unit = unitIndex;
            return;
        }
    }
}

- (NSTimeInterval) timeIntervalFromBase:(NSTimeInterval)base unit:(NSInteger)unitIndex {
    if (unitIndex &amp;gt;= numberOfUnits()) {
        [NSException raise:NSInvalidArgumentException format:@"unitIndex beyond max allowed bounds (%d)", numberOfUnits()];
        return 0;
    }

    return (base * unitIntervals[unitIndex]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This code is identical to the code that was in our previous template, so I won&amp;#8217;t explain it here.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSArray *) templateViews {
    NSMutableArray * views = [[super templateViews] mutableCopy];

    [views addObject:[self unitPopUpButton]];

    NSPopUpButton * operatorView = [views objectAtIndex:1];
    [[operatorView itemAtIndex:0] setTitle:@"is in the last"];
    [[operatorView itemAtIndex:1] setTitle:@"is in the next"];

    return [views autorelease];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our &lt;code&gt;-templateViews&lt;/code&gt; method is almost the same, except that we&amp;#8217;re altering the title of of the operators.  If we were to leave out that bit, then we would see &amp;#8220;matches&amp;#8221; and &amp;#8220;is like&amp;#8221; in the interface.  By changing the title here, we&amp;#8217;re providing a new default value for the operator title.  Note that this can be changed via localization, and more importantly, your &lt;code&gt;NSLocalizedString&lt;/code&gt; macros for generating the strings file &lt;em&gt;should use the values listed here, &lt;strong&gt;not&lt;/strong&gt; the &amp;#8220;matches&amp;#8221; and &amp;#8220;is like&amp;#8221; values&lt;/em&gt;.  Also note that operators show up in the interface in the same order in which they&amp;#8217;re given in the &lt;code&gt;-init&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (double) matchForPredicate:(NSPredicate *)predicate {
    if (![predicate isKindOfClass:[NSComparisonPredicate class]]) { goto errorExit; }

    NSComparisonPredicate * comparison = (NSComparisonPredicate *)predicate;

    NSExpression * left = [comparison leftExpression];
    if (![[self leftExpressions] containsObject:left]) { goto errorExit; }

    NSPredicateOperatorType operator = [comparison predicateOperatorType];
    if (operator != NSGreaterThanPredicateOperatorType &amp;amp;&amp;amp; operator != NSLessThanPredicateOperatorType) { goto errorExit; }

    NSExpression * right = [comparison rightExpression];
    if ([right expressionType] != NSFunctionExpressionType) { goto errorExit; }
    if (![[right function] isEqual:@"castObject:toType:"]) { goto errorExit; }

    NSArray * outerCastArguments = [right arguments];
    //we can pull these out without bounds checking because a CAST() function *must* have 2 arguments

    NSExpression * firstArgument = [outerCastArguments objectAtIndex:0];
    {
        //the first argument must be either an addition or subtraction function
        if ([firstArgument expressionType] != NSFunctionExpressionType) { goto errorExit; }
        if (![[firstArgument function] isEqual:@"add:to:"] &amp;amp;&amp;amp; ![[firstArgument function] isEqual:@"from:subtract:"]) { goto errorExit; }
        NSArray * relativeArguments = [firstArgument arguments];
        NSExpression * firstRelativeArgument = [relativeArguments objectAtIndex:0];
        {
            if ([firstRelativeArgument expressionType] != NSFunctionExpressionType) { goto errorExit; }
            if (![[firstRelativeArgument function] isEqual:@"castObject:toType:"]) { goto errorExit; }
            NSArray * innerCastArguments = [firstRelativeArgument arguments];
            NSExpression * firstInnerArgument = [innerCastArguments objectAtIndex:0];
            if ([firstInnerArgument expressionType] != NSFunctionExpressionType) { goto errorExit; }
            if (![[firstInnerArgument function] isEqual:@"now"]) { goto errorExit; }

            NSExpression * secondInnerArgument = [innerCastArguments objectAtIndex:1];
            if ([secondInnerArgument expressionType] != NSConstantValueExpressionType) { goto errorExit; }
            if (![[secondInnerArgument constantValue] isEqual:@"NSNumber"]) { goto errorExit; }
        }

        NSExpression * secondRelativeArgument = [relativeArguments objectAtIndex:1];
        {
            //the second relative argument is the actual relative difference, so it must be an NSNumber
            if ([secondRelativeArgument expressionType] != NSConstantValueExpressionType) { goto errorExit; }
            if (![[secondRelativeArgument constantValue] isKindOfClass:[NSNumber class]]) { goto errorExit; }
        }
    }

    NSExpression * secondArgument = [outerCastArguments objectAtIndex:1];
    {
        if ([secondArgument expressionType] != NSConstantValueExpressionType) { goto errorExit; }
        if (![[secondArgument constantValue] isEqual:@"NSDate"]) { goto errorExit; }
    }

    return DBL_MAX;

errorExit:
    return 0.0;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a beast of a method.  This is how we determine if this row template recognizes a predicate or not.  Basically what we&amp;#8217;re doing here is making sure that the predicate has a extremely specific structure.  If every requirement is met, then we return &lt;code&gt;DBL_MAX&lt;/code&gt;, which is &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt;&amp;#8217;s way of saying &amp;#8220;I match this predicate better than anyone else ever could&amp;#8221;.  When &lt;code&gt;NSPredicateEditor&lt;/code&gt; finds that multiple row templates match a predicate, it uses the row template that returns the highest match value.  &lt;code&gt;DBL_MAX&lt;/code&gt; is just a cheap way of ensuring that no other template can handle this predicate.&lt;/p&gt;

&lt;p&gt;The expected structure is as follows: (each box is an &lt;code&gt;NSExpression&lt;/code&gt;, and downward arrows indicate arguments to a function expression)&lt;/p&gt;

&lt;p&gt;&lt;img src="http://gallery.me.com/davedelong/100084/NSPredicate%20relative%20dates/web.png?ver=12906606230001" alt="The NSExpression structure for relative dates"/&gt;&lt;/p&gt;

&lt;p&gt;And yes, I use &lt;code&gt;goto&lt;/code&gt; all over the place in that code.  Deal with it.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSPredicate *) predicateWithSubpredicates:(NSArray *)subpredicates {
    NSPredicate * predicate = [super predicateWithSubpredicates:subpredicates];
    if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
        NSComparisonPredicate * comparison = (NSComparisonPredicate *)predicate;

        NSExpression * right = [comparison rightExpression];
        NSNumber * value = [right constantValue];

        NSInteger unit = [[self unitPopUpButton] indexOfSelectedItem];

        NSTimeInterval newInterval = [self timeIntervalFromBase:[value doubleValue] unit:unit];
        value = [NSNumber numberWithDouble:newInterval];
        right = [NSExpression expressionForConstantValue:value];

        //default values are for NSInTheLastPredicateOperatorType
        NSString * function = @"from:subtract:";
        NSPredicateOperatorType newOperator = NSGreaterThanPredicateOperatorType;

        if ([comparison predicateOperatorType] == NSInTheNextPredicateOperatorType) {
            function = @"add:to:";
            newOperator = NSLessThanPredicateOperatorType;
        }

        //"now()" is a function and takes no arguments
        NSExpression * now = [NSExpression expressionForFunction:@"now" arguments:[NSArray array]];

        //CAST(now(), 'NSNumber')
        NSArray * castNowArguments = [NSArray arrayWithObjects:now, [NSExpression expressionForConstantValue:@"NSNumber"], nil];
        NSExpression * castNow = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castNowArguments];

        //CAST(now(), 'NSNumber') [+/-] {a time interval}
        NSArray * relativeTimestampArguments = [NSArray arrayWithObjects:castNow, right, nil];
        NSExpression * relativeTimestamp = [NSExpression expressionForFunction:function arguments:relativeTimestampArguments];

        //CAST(CAST(now(), 'NSNumber') [+/-] {a time interval}, 'NSDate')
        NSArray * castToDateArguments = [NSArray arrayWithObjects:relativeTimestamp, [NSExpression expressionForConstantValue:@"NSDate"], nil];
        NSExpression * castToDate = [NSExpression expressionForFunction:@"castObject:toType:" arguments:castToDateArguments];

        predicate = [NSComparisonPredicate predicateWithLeftExpression:[comparison leftExpression] 
                                                       rightExpression:castToDate 
                                                              modifier:[comparison comparisonPredicateModifier] 
                                                                  type:newOperator 
                                                               options:[comparison options]];
    }
    return predicate;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method is similar in principle to its counterpart in our earlier row template.  Here we&amp;#8217;re letting &lt;code&gt;super&lt;/code&gt; give us a predicate that contains what the user entered into the interval field, and then we extract that number, convert it to an absolute time interval, and then re-create the right expression of the comparison predicate.  We create the expression manually to ensure that the structure returned here exactly matches the structure expected by &lt;code&gt;-matchForPredicate:&lt;/code&gt;.  Notice that we&amp;#8217;re changing our &lt;code&gt;matches&lt;/code&gt; and &lt;code&gt;like&lt;/code&gt; operators to the expected &lt;code&gt;less than&lt;/code&gt; and &lt;code&gt;greater than&lt;/code&gt; versions.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void) setPredicate:(NSPredicate *)predicate {
    if ([predicate isKindOfClass:[NSComparisonPredicate class]]) {
        NSComparisonPredicate * comparison = (NSComparisonPredicate *)predicate;
        /**
         I know that to get here, I must have matched the predicate.
         Therefore I can drill into the comparison predicate structure with reckless abandon!
         **/
        NSExpression * right = [comparison rightExpression];
        NSArray * arguments = [right arguments];

        //this expression is our addition or subtraction function
        NSExpression * relative = [arguments objectAtIndex:0];

        //the second argument to our relative function is our absolute time interval
        NSExpression * intervalExpression = [[relative arguments] objectAtIndex:1];
        NSNumber * interval = [intervalExpression constantValue];

        NSTimeInterval base = 0;
        NSInteger unit = 0;
        [self getBase:&amp;amp;base unit:&amp;amp;unit fromTimeInterval:[interval doubleValue]];

        [[self unitPopUpButton] selectItemAtIndex:unit];

        NSExpression * newRight = [NSExpression expressionForConstantValue:[NSNumber numberWithDouble:base]];
        NSPredicateOperatorType newOperator = NSInTheLastPredicateOperatorType;
        if ([comparison predicateOperatorType] == NSLessThanPredicateOperatorType) {
            newOperator = NSInTheNextPredicateOperatorType;
        }

        predicate = [NSComparisonPredicate predicateWithLeftExpression:[comparison leftExpression] 
                                                       rightExpression:newRight
                                                              modifier:[comparison comparisonPredicateModifier] 
                                                                  type:newOperator 
                                                               options:[comparison options]];
    }
    [super setPredicate:predicate];
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And finally!  When given a predicate, we need to reflect those values in the UI.  Here we&amp;#8217;re simply going to extract the absolute time interval that&amp;#8217;s buried in the &lt;code&gt;rightExpression&lt;/code&gt; and use it to figure out what our base and unit should be.  We also change the operator from &lt;code&gt;greater than&lt;/code&gt; or &lt;code&gt;less than&lt;/code&gt; to &lt;code&gt;likes&lt;/code&gt; or &lt;code&gt;matches&lt;/code&gt;, &lt;em&gt;simply so that the operator popup shows the right value&lt;/em&gt;.  After that, we re-package things, and send it on up to &lt;code&gt;super&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Wrap-up&lt;/h2&gt;

&lt;p&gt;Not too bad, eh?  Grokking this involves a little bit of mental gymnastics, but if you&amp;#8217;re familiar with predicates and their internal structure, most of this code should be really straight-forward.  This was mainly to help connect all those disparate dots and form a coherent picture.  The more you play with these row templates, the more you&amp;#8217;ll truly understand how they interact with each other and their parent predicate editor.  They&amp;#8217;re quite clever little classes, and they can really make our apps that much more &amp;#8220;Mac-like&amp;#8221;.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1677163679</link><guid>http://funwithobjc.tumblr.com/post/1677163679</guid><pubDate>Wed, 24 Nov 2010 21:01:56 -0800</pubDate><category>nspredicateeditor</category></item><item><title>Mathematically evaluating NSStrings</title><description>&lt;p&gt;I&amp;#8217;ve recently posted the code to a project I&amp;#8217;ve written called &lt;strong&gt;&lt;code&gt;DDMathParser&lt;/code&gt;&lt;/strong&gt;.  It&amp;#8217;s a way whereby you can take an &lt;code&gt;NSString&lt;/code&gt; and evaluate it as a mathematical expression.  For example, you can do:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSLog(@"%@", [@"1 + 3 * 4 - 5" numberByEvaluatingString]); //logs "8"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are several other ways to evaluate strings, including methods that allow you to use variables (&lt;code&gt;1 + $a&lt;/code&gt;, and then substitute &lt;code&gt;$a&lt;/code&gt; for a value later).  You can even define custom functions, like &lt;code&gt;mySuperSecretFunction(42)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This was a really fun project, because there were some really interesting challenges to work around (like how can I parse a left associative expression using a recursive descent parser without getting caught in an infinite recursion?).  I&amp;#8217;ll save those for another post.&lt;/p&gt;

&lt;p&gt;For now, go check out the source on github and let me know what you think!&lt;/p&gt;

&lt;p&gt;&lt;a href="http://github.com/davedelong/DDMathParser"&gt;&lt;a href="http://github.com/davedelong/DDMathParser"&gt;http://github.com/davedelong/DDMathParser&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1655852768</link><guid>http://funwithobjc.tumblr.com/post/1655852768</guid><pubDate>Mon, 22 Nov 2010 21:01:24 -0800</pubDate><category>parser</category><category>math</category></item><item><title>Creating a simple NSPredicateEditorRowTemplate</title><description>&lt;p&gt;&lt;code&gt;NSPredicateEditor&lt;/code&gt; is a great class, provided you figure out how it works.  There&amp;#8217;s a fair amount of documentation as to what&amp;#8217;s going on, but if you ever want to do something beyond what&amp;#8217;s possible through configuration in Interface Builder, you&amp;#8217;re probably going to spend several hours playing with things until you get it right.&lt;/p&gt;

&lt;p&gt;Hopefully, I can help cut down that time.&lt;/p&gt;

&lt;h3&gt;What&amp;#8217;s going on under the hood&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;NSPredicateEditor&lt;/code&gt; is a subclass of &lt;code&gt;NSRuleEditor&lt;/code&gt;.  However, they really don&amp;#8217;t behave the same way at all, so knowing that doesn&amp;#8217;t really give you much insight (that I&amp;#8217;ve found).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NSPredicateEditor&lt;/code&gt; uses a template mechanism for displaying an &lt;code&gt;NSPredicate&lt;/code&gt;.  These templates are instances of &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt; (go figure).  Each row template (with one exception) displays a single &lt;code&gt;NSComparisonPredicate&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The exception to this is the built-in row template for handling &lt;code&gt;NSCompoundPredicates&lt;/code&gt;.  We&amp;#8217;re going to ignore this template in this post and focus on customizing templates for comparison predicates.&lt;/p&gt;

&lt;p&gt;When the &lt;code&gt;NSPredicateEditor&lt;/code&gt; gets a new predicate object (via &lt;code&gt;-setObjectValue:&lt;/code&gt;), it has to figure out what row templates it needs.  It&amp;#8217;s a pretty simple process:  The editor simply asks each one of its row templates whether it recognizes the &lt;code&gt;NSPredicate&lt;/code&gt;.  (&lt;a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSPredicateEditorRowTemplate_class/Reference/NSPredicateEditorRowTemplate.html#//apple_ref/doc/uid/TP40004605-CH1-SW2"&gt;&lt;code&gt;-matchForPredicate:&lt;/code&gt;&lt;/a&gt;)  If the template responds affirmatively, then the editor will &lt;code&gt;-copy&lt;/code&gt; the template (this is why row templates conform to &lt;code&gt;&amp;lt;NSCopying&amp;gt;&lt;/code&gt;) and invoke &lt;code&gt;-setPredicate:&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;-setPredicate:&lt;/code&gt; is simply going to extract the predicate&amp;#8217;s &lt;code&gt;leftExpression&lt;/code&gt;, &lt;code&gt;predicateOperatorType&lt;/code&gt;, and &lt;code&gt;rightExpression&lt;/code&gt;.  These values will then be set into the UI.&lt;/p&gt;

&lt;h3&gt;The UI&lt;/h3&gt;

&lt;p&gt;One of the interesting things about row templates is that they do not inherit from &lt;code&gt;NSView&lt;/code&gt;.  In other words, the actual &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt; object is never (indeed cannot be) displayed to the user.  So what is it the user is seeing?  It&amp;#8217;s the row template&amp;#8217;s &lt;a href="http://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSPredicateEditorRowTemplate_class/Reference/NSPredicateEditorRowTemplate.html#//apple_ref/doc/uid/TP40004605-CH1-SW1"&gt;&lt;code&gt;-templateViews&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;By default, an &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt; provides 3 template views:  an &lt;code&gt;NSPopUpButton&lt;/code&gt;, a second &lt;code&gt;NSPopUpButton&lt;/code&gt;, and either a third &lt;code&gt;NSPopUpButton&lt;/code&gt; or some sort of user-interactable view, like an &lt;code&gt;NSDatePicker&lt;/code&gt; or an &lt;code&gt;NSTextField&lt;/code&gt;.  The first popup lists all of the possible left-hand &lt;code&gt;NSExpressions&lt;/code&gt;, the second holds the operators, and the third view holds the right-hand &lt;code&gt;NSExpressions&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;These views are received by the &lt;code&gt;NSPredicateEditor&lt;/code&gt; and shown in the UI.  Their styles are manipulated to make them have the &amp;#8220;rounded rect&amp;#8221; appearance, and their frames are changed to make them fit in the row.  The main attribute that&amp;#8217;s useful to configure is the frame width of the right-hand view.  If the third view is an &lt;code&gt;NSDatePicker&lt;/code&gt;, you may alter the width of the view to allow room for specifying a time in addition to the date.  (By default, an &lt;code&gt;NSDatePicker&lt;/code&gt; only allows date selection)&lt;/p&gt;

&lt;p&gt;Customizing the UI is a simple matter of overriding the &lt;code&gt;-templateViews&lt;/code&gt; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSArray *) templateViews {
  NSMutableArray * templateViews = [[super templateViews] mutableCopy];

  //at this point, you have a mutable array of views.
  //you can add views, remove views, alter appropriate properties of existing views, etc.

  return [templateViews autorelease];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;However, you need to be careful with this.  &lt;code&gt;-templateViews&lt;/code&gt; is called more than once, so if you&amp;#8217;re instantiating a new view each time this is invoked, you may end up allocating too many views and not know which one is actually being shown on the UI.  For this reason I prefer a &amp;#8220;lazy allocation&amp;#8221; method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSView *) myExtraView {
  if (myExtraView == nil) {
    myExtraView = [[MyExtraView alloc] init...];
    ...
  }
  return myExtraView;
}

- (NSArray *) templateViews {
  NSMutableArray * templateViews = [[super templateViews] mutableCopy];

  [templateViews addObject:[self myExtraView]];

  return [templateViews autorelease];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now I know that the &lt;code&gt;myExtraView&lt;/code&gt; object will only be allocated once per instance of my row template, and I can always go access the view directly to retrieve information about what the user has manipulated.&lt;/p&gt;

&lt;p&gt;&amp;lt;caution&amp;gt;&lt;/p&gt;

&lt;p&gt;If you&amp;#8217;re &lt;a href="http://tumblr.com/xqooiw0ue"&gt;localizing this &lt;code&gt;NSPredicateEditor&lt;/code&gt;&lt;/a&gt;, then you must consider this:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;When specifying the translated value of a row template, &lt;em&gt;the number of positional specifiers in the translated value must be equal to the number of views returned from &lt;code&gt;-templateViews&lt;/code&gt;&lt;/em&gt;.  If not, the editor will fail to localize that row.&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;In other words, if you have a custom &lt;code&gt;-templateViews&lt;/code&gt; method that adds a fourth view, then your translated string for this row must have &lt;code&gt;%1$@&lt;/code&gt;, &lt;code&gt;%2$@&lt;/code&gt;, &lt;code&gt;%3$@&lt;/code&gt;, and &lt;code&gt;%4$@&lt;/code&gt; (with the translated values interspersed appropriately).  &lt;code&gt;%1$@&lt;/code&gt; will be replaced with the first view in the array returned from &lt;code&gt;-templateViews&lt;/code&gt;, &lt;code&gt;%2$@&lt;/code&gt; will be replaced with the second view, etc.&lt;/p&gt;

&lt;p&gt;&amp;lt;/caution&amp;gt;&lt;/p&gt;

&lt;p&gt;On a final point regarding &lt;code&gt;-templateViews&lt;/code&gt;, I&amp;#8217;ve found that I rarely have an occasion to alter the first or second views returned by &lt;code&gt;super&lt;/code&gt;.  Your mileage may vary, but I&amp;#8217;ve generally found that it&amp;#8217;s best to leave them alone.&lt;/p&gt;

&lt;h2&gt;Building a custom row template&lt;/h2&gt;

&lt;p&gt;Now that we understand the basics of what&amp;#8217;s going on, let&amp;#8217;s build a simple &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt;.  To keep things simple, we&amp;#8217;re going to build a row template that allows us to compare against an &lt;code&gt;NSTimeInterval&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;The Interface&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;@interface DDTimeIntervalRowTemplate : NSPredicateEditorRowTemplate {
    NSPopUpButton * unitPopUpButton;
}

- (id) initWithLeftExpressions:(NSArray *)leftExpressions;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It&amp;#8217;s pretty simple.  We inherit from &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt;, we provide a custom initializer (since we&amp;#8217;ll be instantiating the template programmatically), and we have one instance variable for holding on to our extra &lt;code&gt;NSPopUpButton&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;The Implementation&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;@implementation DDTimeIntervalRowTemplate

- (id) initWithLeftExpressions:(NSArray *)leftExpressions {
    NSAttributeType rightType = NSDoubleAttributeType; //NSTimeInterval is a typedef'd double
    NSComparisonPredicateModifier modifier = NSDirectPredicateModifier; //don't need "ANY" or "ALL"
    NSArray * operators = [NSArray arrayWithObjects:
                           [NSNumber numberWithUnsignedInteger:NSLessThanPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSLessThanOrEqualToPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSGreaterThanPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSGreaterThanOrEqualToPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSEqualToPredicateOperatorType],
                           [NSNumber numberWithUnsignedInteger:NSNotEqualToPredicateOperatorType],
                           nil];
    NSUInteger options = 0;
    return [super initWithLeftExpressions:leftExpressions
             rightExpressionAttributeType:rightType
                                 modifier:modifier
                                operators:operators
                                  options:options];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Again, this should be fairly straight-forward.  We&amp;#8217;re creating a row template with the left expressions given to the initializer.  These left expressions will be compared against a user-entered &lt;code&gt;double&lt;/code&gt; value.  We&amp;#8217;ll be doing a direct comparison (simply put: &lt;code&gt;&amp;lt;left expression&amp;gt; &amp;lt;comparison operator&amp;gt; &amp;lt;user-entered value&amp;gt;&lt;/code&gt;), and we&amp;#8217;re supporting the standard numeric operators:  &lt;code&gt;&amp;lt;&lt;/code&gt;, &lt;code&gt;&amp;lt;=&lt;/code&gt;, &lt;code&gt;&amp;gt;&lt;/code&gt;, &lt;code&gt;&amp;gt;=&lt;/code&gt;, &lt;code&gt;=&lt;/code&gt;, and &lt;code&gt;!=&lt;/code&gt;.  The &lt;code&gt;options&lt;/code&gt; bit is only useful for string comparison (it&amp;#8217;s how you specific case insensitivity or diacritic insensitivity, etc).  Once we&amp;#8217;ve got everything specified, we&amp;#8217;ll let &lt;code&gt;super&lt;/code&gt;&amp;#8217;s initializer finish everything off for us.&lt;/p&gt;

&lt;p&gt;Continuing&amp;#8230;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;static NSString * unitNames[] = {@"seconds", @"minutes", @"hours", @"days", @"weeks"};
static NSInteger unitIntervals[] = {1, 60, 3600, 86400, 604800};
#define numberOfUnits() (sizeof(unitNames)/sizeof(unitNames[0]))

- (NSPopUpButton *) unitPopUpButton {
    if (unitPopUpButton == nil) {
        unitPopUpButton = [[NSPopUpButton alloc] initWithFrame:NSZeroRect pullsDown:NO];

        NSMenu * unitMenu = [unitPopUpButton menu];
        for (int i = 0; i &amp;lt; numberOfUnits(); ++i) {
            [unitMenu addItemWithTitle:unitNames[i] action:NULL keyEquivalent:@""];
        }
    }
    return unitPopUpButton;
}

- (void) dealloc {
    [unitPopUpButton release];
    [super dealloc];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method will be our lazy initializer for our unit popup button (to ensure that we only allocate one button per instance of the row template).  The button has 5 items in its menu, each representing a different unit of time measurement.  We also have a static &lt;code&gt;NSInteger&lt;/code&gt; array that reflects the number of seconds in each unit (ie, one day is 86,400 seconds).&lt;/p&gt;

&lt;p&gt;One thing that&amp;#8217;s interesting here is that we&amp;#8217;re initializing our &lt;code&gt;NSPopUpButton&lt;/code&gt; with &lt;code&gt;NSZeroRect&lt;/code&gt;.  We can do this because &lt;code&gt;NSPredicateEditor&lt;/code&gt; will adjust the origin of the view to be in the appropriate spot relative to the other views and the size to fit the content.  In other words, the frame will be taken care of for us.&lt;/p&gt;

&lt;p&gt;And of course, since we&amp;#8217;ve allocated an object, we must be sure to &lt;code&gt;release&lt;/code&gt; it in our &lt;code&gt;-dealloc&lt;/code&gt; method.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void) getBase:(NSTimeInterval *)base unit:(NSInteger *)unit fromTimeInterval:(NSTimeInterval)timeInterval {
    if (base == nil || unit == nil) {
        [NSException raise:NSInvalidArgumentException format:@"base and unit cannot be nil"];
    }

    for (NSInteger unitIndex = numberOfUnits() - 1; unitIndex &amp;gt;= 0; unitIndex--) {
        if (timeInterval &amp;gt;= unitIntervals[unitIndex]) {
            *base = timeInterval / unitIntervals[unitIndex];
            *unit = unitIndex;
            return;
        }
    }
}

- (NSTimeInterval) timeIntervalFromBase:(NSTimeInterval)base unit:(NSInteger)unitIndex {
    if (unitIndex &amp;gt;= numberOfUnits()) {
        [NSException raise:NSInvalidArgumentException format:@"unitIndex beyond max allowed bounds (%d)", numberOfUnits()];
        return 0;
    }

    return (base * unitIntervals[unitIndex]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;These 2 methods are simply convenience methods.  The first method will convert an &lt;code&gt;NSTimeInterval&lt;/code&gt; into a unit and a base.  For example, if given &lt;code&gt;172800&lt;/code&gt; as the interval, it will return a base of &lt;code&gt;2&lt;/code&gt; and a unit of &lt;code&gt;3&lt;/code&gt;, to represent &lt;code&gt;2 days&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The second method is simply the inverse.  Given a base and a unit, it will turn it into an absolute &lt;code&gt;NSTimeInterval&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now for the fun stuff!&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSArray *) templateViews {
    NSMutableArray * views = [[super templateViews] mutableCopy];

    [views addObject:[self unitPopUpButton]];

    return [views autorelease];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is about as simple as it gets.  When we&amp;#8217;re asked for what views to display in the interface, we&amp;#8217;re going to return the three views provided by &lt;code&gt;super&lt;/code&gt; (two popup buttons and an &lt;code&gt;NSTextField&lt;/code&gt;) and add a fourth button of our own (the popup button denoting a unit of time).&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (NSPredicate *) predicateWithSubpredicates:(NSArray *)subpredicates {
    NSPredicate * p = [super predicateWithSubpredicates:subpredicates];
    if ([p isKindOfClass:[NSComparisonPredicate class]]) {
        NSComparisonPredicate * comparison = (NSComparisonPredicate *)p;

        NSExpression * right = [comparison rightExpression];
        NSNumber * value = [right constantValue];

        NSInteger unit = [[self unitPopUpButton] indexOfSelectedItem];

        NSTimeInterval newInterval = [self timeIntervalFromBase:[value doubleValue] unit:unit];
        value = [NSNumber numberWithDouble:newInterval];
        right = [NSExpression expressionForConstantValue:value];

        p = [NSComparisonPredicate predicateWithLeftExpression:[comparison leftExpression] 
                                               rightExpression:right 
                                                      modifier:[comparison comparisonPredicateModifier] 
                                                          type:[comparison predicateOperatorType] 
                                                       options:[comparison options]];
    }
    return p;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method is one of the two at the heart of our custom template.  Via this method, we&amp;#8217;re translating what&amp;#8217;s on the UI into an &lt;code&gt;NSPredicate&lt;/code&gt;.  For the most part, we&amp;#8217;re going to let &lt;code&gt;super&lt;/code&gt; handle the implementation, with one minor alteration.  By invoking &lt;code&gt;super&lt;/code&gt; on this, we&amp;#8217;re going to get back an &lt;code&gt;NSPredicate&lt;/code&gt; of the form &lt;code&gt;&amp;lt;left expression&amp;gt; &amp;lt;operator&amp;gt; &amp;lt;value of textfield&amp;gt;&lt;/code&gt;.  We need to extract the &lt;code&gt;rightExpression&lt;/code&gt;, who&amp;#8217;s &lt;code&gt;constantValue&lt;/code&gt; will be an &lt;code&gt;NSNumber&lt;/code&gt; representing what was in the textfield.  It is the &lt;code&gt;doubleValue&lt;/code&gt; of this &lt;code&gt;NSNumber&lt;/code&gt; that becomes the &lt;code&gt;base&lt;/code&gt;, and the index of our &lt;code&gt;unitPopUpButton&lt;/code&gt; is our &lt;code&gt;unit&lt;/code&gt;.  Once we have those two values, we can run them through our conversion method, then rebuild our comparison predicate.  This new comparison predicate will be exactly the same as the predicate returned by &lt;code&gt;super&lt;/code&gt;, with the single change of having the &lt;code&gt;constantValue&lt;/code&gt; of the &lt;code&gt;rightExpression&lt;/code&gt; modified.&lt;/p&gt;

&lt;p&gt;Finally&amp;#8230;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;- (void) setPredicate:(NSPredicate *)newPredicate {
    if ([newPredicate isKindOfClass:[NSComparisonPredicate class]]) {

        NSComparisonPredicate * comparison = (NSComparisonPredicate *)newPredicate;

        NSExpression * right = [comparison rightExpression];
        NSNumber * value = [right constantValue];

        NSTimeInterval base = 0;
        NSInteger unit = 0;
        [self getBase:&amp;amp;base unit:&amp;amp;unit fromTimeInterval:[value doubleValue]];

        value = [NSNumber numberWithDouble:base];
        right = [NSExpression expressionForConstantValue:value];

        [[self unitPopUpButton] selectItemAtIndex:unit];

        newPredicate = [NSComparisonPredicate predicateWithLeftExpression:[comparison leftExpression] 
                                                          rightExpression:right 
                                                                 modifier:[comparison comparisonPredicateModifier] 
                                                                     type:[comparison predicateOperatorType] 
                                                                  options:[comparison options]];
    }

    [super setPredicate:newPredicate];
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the final method that we need to implement.  This method will take an &lt;code&gt;NSPredicate&lt;/code&gt; and extract various values from it to reflect in the UI.  Like its inverse &lt;code&gt;-predicateWithSubpredicates:&lt;/code&gt;, we&amp;#8217;re going to let &lt;code&gt;super&lt;/code&gt; handle most of the work.  However, we need to do a bit of manipulation first.  We&amp;#8217;re going to extract the &lt;code&gt;constantValue&lt;/code&gt; of the comparison predicate&amp;#8217;s &lt;code&gt;rightExpression&lt;/code&gt;.  This &lt;code&gt;NSNumber&lt;/code&gt; is the absolute time interval, in seconds.  We&amp;#8217;re going to take that time interval and run it through our conversion method to turn it into a base and a unit.  The unit is used to select the appropriate item in the &lt;code&gt;unitPopUpButton&lt;/code&gt;, and the base is put back into the &lt;code&gt;NSPredicate&lt;/code&gt;.  When we pass this new predicate up to &lt;code&gt;super&lt;/code&gt;, the base will be placed inside the text field (the third view returned from &lt;code&gt;-templateViews&lt;/code&gt;).&lt;/p&gt;

&lt;h2&gt;Using this template&lt;/h2&gt;

&lt;p&gt;Now that we have this template, we have to actually &lt;em&gt;use&lt;/em&gt; it.  Fortunately, it&amp;#8217;s pretty simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSPredicateEditor * editor = ...; //some NSPredicateEditor. perhaps an IBOutlet?
NSMutableArray * rowTemplates = [[editor rowTemplates] mutableCopy];

NSArray * leftExpressions = [NSArray arrayWithObject:[NSExpression expressionForKeyPath:@"duration"]];
DDTimeIntervalRowTemplate * intervalTemplate = [[DDTimeIntervalRowTemplate alloc] initWithLeftExpressions:leftExpressions];
[rowTemplates addObject:intervalTemplate];
[intervalTemplate release];

[editor setRowTemplates:rowTemplates];
[rowTemplates release];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This should be fairly easy to understand.  We&amp;#8217;re simply adding an instance of &lt;code&gt;DDTimeIntervalRowTemplate&lt;/code&gt; to the list of templates available to our &lt;code&gt;NSPredicateEditor&lt;/code&gt;.  This row template recognizes one left expression, the keyPath &lt;code&gt;@"duration"&lt;/code&gt;.  This means that all predicates generated by this row template will be of the form &lt;code&gt;duration &amp;lt;operator&amp;gt; &amp;lt;time interval&amp;gt;&lt;/code&gt;.  Pretty easy.&lt;/p&gt;

&lt;h2&gt;Localizing this template&lt;/h2&gt;

&lt;p&gt;To localize this row template, we&amp;#8217;ll need the following somewhere in a comment:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSLocalizedStringFromTable(@"%[duration]@ %[is, is not, is greater than, is less than, is greater than or equal to, is less than or equal to]@ %@ %[seconds, minutes, hours, days, weeks]@", @"Predicate", @"the text of the duration template")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will generate a rather lengthy strings file (30 different key-value pairs), with each value having four positional specifiers (as was mentioned above), one for each of the views returned from &lt;code&gt;-templateViews&lt;/code&gt;.  For a more complete explanation of how localizing a predicate editor, see my earlier post on that very topic.&lt;/p&gt;

&lt;h2&gt;Wrap-Up&lt;/h2&gt;

&lt;p&gt;So there you have it!  This may be a rather simple and contrived example, but a useful one.  Hopefully this will help you as you wrap your brain around &lt;code&gt;NSPredicateEditor&lt;/code&gt; and its supporting classes.  There are still a couple gotchas, but we&amp;#8217;ll learn about those in another post.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1646098126</link><guid>http://funwithobjc.tumblr.com/post/1646098126</guid><pubDate>Sun, 21 Nov 2010 23:00:46 -0800</pubDate><category>nspredicateeditor</category></item><item><title>Abusing NSPredicate</title><description>&lt;p&gt;&lt;code&gt;NSPredicate&lt;/code&gt; is a nifty class.  It&amp;#8217;s intended use is to be an objected-oriented way of expressing a truth statement.  We see this being used with things like &lt;code&gt;-[NSArray filteredArrayUsingPredicate:]&lt;/code&gt;, &lt;code&gt;-[NSFetchRequest setPredicate:]&lt;/code&gt;, and more.  &lt;code&gt;NSPredicate&lt;/code&gt;, however, can offer us a lot more.&lt;/p&gt;

&lt;p&gt;There are 2 things that make &lt;code&gt;NSPredicate&lt;/code&gt; so insanely awesome:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Its string parser&lt;/li&gt;
&lt;li&gt;The evaluation power of &lt;code&gt;NSExpression&lt;/code&gt; (one of &lt;code&gt;NSPredicate&lt;/code&gt;&amp;#8217;s support classes)&lt;/li&gt;
&lt;/ol&gt;&lt;h3&gt;NSPredicate Parsing&lt;/h3&gt;

&lt;p&gt;One of the best things about &lt;code&gt;NSPredicate&lt;/code&gt; is its parsing engine.  Given a well-formatted &lt;code&gt;NSString&lt;/code&gt;, &lt;code&gt;NSPredicate&lt;/code&gt; will turn it into a tree of &lt;code&gt;NSCompoundPredicate&lt;/code&gt; and &lt;code&gt;NSComparisonPredicate&lt;/code&gt; objects.  This can be used to our advantage.  If we have a string that represent some boolean expression, we can tap &lt;code&gt;NSPredicate&lt;/code&gt; to parse it for us and give us back an organized syntax tree.&lt;/p&gt;

&lt;p&gt;For this example, let&amp;#8217;s consider the following:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(a | b) &amp;amp; c | (b | d)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If we just try to run this through the predicate parser, we&amp;#8217;ll get an exception, for 2 reasons:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;A predicate is a truth statement.  This expression is simply a value.  It is not being compared to anything, and as such does not represent a true or false statement, but simply a value.&lt;/li&gt;
&lt;li&gt;Each sub-expression of a predicate must itself be a predicate.  Since &amp;#8220;&lt;code&gt;c&lt;/code&gt;&amp;#8221; (for example) is not being compared to anything, it is not a valid statement.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Fixing the first problem is easy.  We can just tack &amp;#8220;&lt;code&gt;= 0&lt;/code&gt;&amp;#8221; onto the end of the statement:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(a | b) &amp;amp; c | (b | d) = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As for fixing the second, we can do that with a little bit of find-and-replace by regular expression.  For simplicity, we&amp;#8217;ll say that each one of these identifiers (&lt;code&gt;a&lt;/code&gt;, &lt;code&gt;b&lt;/code&gt;, &lt;code&gt;c&lt;/code&gt;, and &lt;code&gt;d&lt;/code&gt;) must be alphanumeric.  We can then use something like &lt;a href="http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html"&gt;&lt;code&gt;NSRegularExpression&lt;/code&gt;&lt;/a&gt; (on iOS) or &lt;a href="http://regexkit.com"&gt;RegexKit&lt;/a&gt; (on Mac) to replace &amp;#8220;&lt;code&gt;([a-z0-9]+)&lt;/code&gt;&amp;#8221; with &amp;#8220;&lt;code&gt;\1 = 0&lt;/code&gt;&amp;#8221;, thereby giving us:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(a = 0 | b = 0) &amp;amp; c = 0 | (b = 0 | d = 0) = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We can now run this through &lt;code&gt;+[NSPredicate predicateWithFormat:]&lt;/code&gt; to get our parsed tree.  From there you can recursively walk the tree and manipulate things as much as you like.&lt;/p&gt;

&lt;h3&gt;NSExpression Solving&lt;/h3&gt;

&lt;p&gt;Let&amp;#8217;s say you have a string that contains some sort of mathematical statement.  Perhaps it&amp;#8217;s user-entered, or perhaps it&amp;#8217;s dynamically generated.  For our purposes, we&amp;#8217;re going to use:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;22/7.0 + (13*42) - 1024
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Our calculator shows us that we should be getting &lt;code&gt;-474.857142857142857&lt;/code&gt; as the result.&lt;/p&gt;

&lt;p&gt;But how can we evaluate this dynamically?  Well, you could use something like Graham Cox&amp;#8217;s excellent &lt;a href="http://apptree.net/parser.htm"&gt;&lt;code&gt;GCMathParser&lt;/code&gt;&lt;/a&gt; to parse and evaluate it, but this has a limitation: it&amp;#8217;s a bit difficult (read: nearly impossible) to extend to use functions not supported by the parser.&lt;/p&gt;

&lt;p&gt;Fortunately, we can abuse &lt;code&gt;NSPredicate&lt;/code&gt; to do the work for us.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;NSPredicate&lt;/code&gt; has a wonderful parsing engine (which we&amp;#8217;ve already abused), and it builds a tree built out of &lt;code&gt;NSExpression&lt;/code&gt; objects, which have this wonderful method called &lt;code&gt;-expressionValueWithObject:context:&lt;/code&gt; which will evaluate everything for us.  Unfortunately, there&amp;#8217;s no way to build an &lt;code&gt;NSExpression&lt;/code&gt; tree out of an arbitrary &lt;code&gt;NSString&lt;/code&gt;.  However, &lt;code&gt;NSPredicate&lt;/code&gt; &lt;em&gt;can&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;So we just need to make out statement into a predicate, run it through the parser, and extract the appropriate value!  This is really simple.  To make something into a predicate, we simply need to add an operator and a comparison value:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;22/7.0 + (13*42) - 1024 = 0
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, we can pump it through &lt;code&gt;NSPredicate&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSPredicate * parsed = [NSPredicate predicateWithFormat:@"22/7.0 + (13*42) - 1024 = 0"];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We know that this is an &lt;code&gt;NSComparisonPredicate&lt;/code&gt; (since it&amp;#8217;s of the form &lt;code&gt;&amp;lt;expression&amp;gt; &amp;lt;operator&amp;gt; &amp;lt;expression&amp;gt;&lt;/code&gt;), so we can simply extract the &lt;code&gt;leftExpression&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSExpression * left = [(NSComparisonPredicate *)parsed leftExpression];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And finally, we can now evaluate it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSNumber * result = [left expressionValueWithObject:nil context:nil];
NSLog(@"result: %@", result);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Wonderfully, this logs &lt;code&gt;-474.8571428571429&lt;/code&gt;, which is exactly what we were hoping for.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1553469975</link><guid>http://funwithobjc.tumblr.com/post/1553469975</guid><pubDate>Fri, 12 Nov 2010 09:31:27 -0800</pubDate><category>nspredicate</category><category>nsexpression</category></item><item><title>Defining custom key path operators</title><description>&lt;p&gt;(This was prompted by &lt;a href="http://stackoverflow.com/q/4100458/115730"&gt;a recent question&lt;/a&gt; on &lt;a href="http://stackoverflow.com"&gt;StackOverflow&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;&lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/KeyValueCoding.html"&gt;Key-value coding&lt;/a&gt; is one of my more favorite things about Cocoa (up there with &lt;code&gt;NSPredicate&lt;/code&gt;).  Basically, it allows you to access properties of objects by name (ie, as a string) rather than invoking a method (er&amp;#8230; &lt;em&gt;sending a message&lt;/em&gt;) directly.&lt;/p&gt;

&lt;p&gt;Along with accessing properties, you can (with some limitations) retrieve calculated values (not strictly properties) about these objects.  For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSArray * anArray = .... //an NSArray of NSNumbers 
NSNumber * count = [anArray valueForKeyPath:@"@count"];
NSNumber * max = [anArray valueForKeyPath:@"@max.self"];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There are several others, like &lt;code&gt;@sum&lt;/code&gt;, &lt;code&gt;@avg&lt;/code&gt;, and some collection-oriented operators.  For a full list, see &lt;a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueCoding/Concepts/ArrayOperators.html%23//apple_ref/doc/uid/20002176-BAJEAIEE"&gt;this page in the documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;But what if you want something else?  What if you wanted to do something like &lt;code&gt;@size&lt;/code&gt;, which we&amp;#8217;ll define as the size (in bytes) that the object directly occupies in memory?  To answer this question, let&amp;#8217;s see if we can figure out what&amp;#8217;s going on with &lt;code&gt;NSArray&lt;/code&gt;, and take some clues from that.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#import &amp;lt;objc/runtime.h&amp;gt;

unsigned int methodCount = 0;
Method * methods = class_copyMethodList([NSArray class], &amp;amp;methodCount);
for (int i = 0; i &amp;lt; methodCount; ++i) {
  Method m = methods[i];
  NSLog(@"%@", NSStringFromSelector(method_getName(m)));
}
free(methods);
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When we run this, we&amp;#8217;re going to get a bunch of methods listed, but there are some interesting ones that should catch our eye:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;_distinctUnionOfSetsForKeyPath:
_distinctUnionOfObjectsForKeyPath:
_distinctUnionOfArraysForKeyPath:
_unionOfSetsForKeyPath:
_unionOfArraysForKeyPath:
_unionOfObjectsForKeyPath:
_minForKeyPath:
_maxForKeyPath:
_countForKeyPath:
_avgForKeyPath:
_sumForKeyPath:
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Those look familiar!  Specifically, they look like our collection operators that have undergone a bit of string manipulation.  It looks like the &lt;code&gt;@&lt;/code&gt; has been replaced with an &lt;code&gt;_&lt;/code&gt; and the string &lt;code&gt;ForKeyPath:&lt;/code&gt; has been appended.  (These methods also appear on &lt;code&gt;NSSet&lt;/code&gt;)&lt;/p&gt;

&lt;p&gt;So theoretically, if we just add a method that matches this format (&lt;code&gt;_&lt;/code&gt; + {nameOfKeyPath} + &lt;code&gt;ForKeyPath:&lt;/code&gt;), it should work!&lt;/p&gt;

&lt;p&gt;A bit more introspection reveals that these methods return an object, which makes sense because &lt;code&gt;valueForKeyPath:&lt;/code&gt; also returns an object (&lt;code&gt;id&lt;/code&gt;).  We need to do the same.&lt;/p&gt;

&lt;p&gt;Here we go (we&amp;#8217;d need an identical category for &lt;code&gt;NSSet&lt;/code&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#import &amp;lt;objc/runtime.h&amp;gt;

@interface NSArray (CustomKVCOperator)

- (id) _sizeForKeyPath:(NSString *)keyPath;

@end

@implementation NSArray (CustomKVCOperator)

- (id) _sizeForKeyPath:(NSString *)keyPath {
  id keyPathValue = [self valueForKeyPath:keyPath];
  size_t instanceSize = class_getInstanceSize([keyPathValue class]);
  return [NSNumber numberWithInt:instanceSize];
}

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we can test this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSArray * array = [NSArray array];
NSLog(@"size: %@", [array valueForKeyPath:@"@size.self"]); //logs "8"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It worked!  (Honestly, the first time I tried this I was totally surprised that it did)&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;While this example is pretty contrived, it&amp;#8217;s not difficult to imagine a scenario when it could be useful.  Unfortunately, this only works on collections.  You can&amp;#8217;t (for example) add a &lt;code&gt;_sqrtForKeyPath:&lt;/code&gt; method to &lt;code&gt;NSNumber&lt;/code&gt; and hope to use &lt;code&gt;@sqrt&lt;/code&gt; as a keyPath operator on &lt;code&gt;NSNumber&lt;/code&gt;.  Bummer. :(&lt;/p&gt;

&lt;p&gt;As always with things like this, a word of caution: this works, but only because we rely on some undocumented behavior.  This is by no means something that would get an app rejected from the App Stores, but be aware that Apple can change the implementation of &lt;code&gt;valueForKeyPath:&lt;/code&gt; at any time.&lt;/p&gt;

&lt;p&gt;A safer (albeit more complex) way to achieve this same functionality would be to subclass the appropriate collection (&lt;code&gt;NSArray&lt;/code&gt; or &lt;code&gt;NSSet&lt;/code&gt;) and override the &lt;code&gt;valueForKeyPath:&lt;/code&gt; method.  However, this introduces new problems, since both are class clusters, and subclassing a class cluster is fraught with peril.&lt;/p&gt;

&lt;p&gt;At any rate, if you find yourself wishing that you had &lt;code&gt;@stdDev&lt;/code&gt; or &lt;code&gt;@productOfEveryThirdNumber&lt;/code&gt; operators, now you know.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1527111790</link><guid>http://funwithobjc.tumblr.com/post/1527111790</guid><pubDate>Tue, 09 Nov 2010 12:27:53 -0800</pubDate><category>key-value-coding</category></item><item><title>Mike Ash: Creating Classes at Runtime</title><description>&lt;a href="http://mikeash.com/pyblog/friday-qa-2010-11-6-creating-classes-at-runtime-in-objective-c.html"&gt;Mike Ash: Creating Classes at Runtime&lt;/a&gt;: &lt;p&gt;Another great article by Mike Ash that’s an expansion on my earlier article about dynamic subclassing.&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1488898856</link><guid>http://funwithobjc.tumblr.com/post/1488898856</guid><pubDate>Fri, 05 Nov 2010 10:21:08 -0700</pubDate><category>runtime</category></item><item><title>Followup to Localizing NSPredicateEditor</title><description>&lt;p&gt;To expand a little bit on my previous post, here&amp;#8217;s a little bit more information:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;p&gt;If you ever forget the format to put in the &lt;code&gt;NSLocalizedString()&lt;/code&gt; macros, you can do the following:&lt;br/&gt;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;predicateEditor = ... //an NSPredicateEditor
NSData * stringsData = [predicateEditor _generateFormattingDictionaryStringsFile];
NSString * strings = [[NSString alloc] initWithData:stringsData encoding:NSUTF16StringEncoding];
[strings writeToFile:@"/path/to/Predicate.strings" encoding:NSUTF16StringEncoding error:nil];
[strings release];&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is relying on an undocumented method of &lt;code&gt;NSPredicateEditor&lt;/code&gt;, but will work fine to simply generate the strings data.  As always, you should probably not use this in shipping code (especially with the imminent launch of the Mac App Store).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;.strings&lt;/code&gt; file used by the &lt;code&gt;NSPredicateEditor&lt;/code&gt; must not contain any other localizations.  In other words, you must use the file for localizing &lt;em&gt;only&lt;/em&gt; the editor.  If you need to localize other parts of your application, their strings must be in a separate &lt;code&gt;.strings&lt;/code&gt; file.  (The sample, mentioned below, uses the &lt;code&gt;NSLocalizedStringFromTable()&lt;/code&gt; macro to specify a custom strings file called &lt;code&gt;Predicate.strings&lt;/code&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I&amp;#8217;ve created an example project (which was the demo shown during my session at &lt;a href="http://mactech.com/conference"&gt;MacTech Conference 2010&lt;/a&gt;) to illustrate both creating a custom &lt;code&gt;NSPredicateEditorRowTemplate&lt;/code&gt; and localizing the predicate editor.  You can download it from my website:  &lt;a href="http://davedelong.com/portfolio"&gt;&lt;a href="http://davedelong.com/portfolio"&gt;http://davedelong.com/portfolio&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Most of what learned regarding localizing &lt;code&gt;NSPredicateEditor&lt;/code&gt; was gleaned from &lt;a href="http://www.cocoabuilder.com/archive/cocoa/221219-getting-localized-nspredicateeditor.html"&gt;this email thread&lt;/a&gt; and the linked sample project.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://funwithobjc.tumblr.com/post/1488710860</link><guid>http://funwithobjc.tumblr.com/post/1488710860</guid><pubDate>Fri, 05 Nov 2010 09:42:36 -0700</pubDate><category>nspredicateeditor</category><category>localization</category></item><item><title>Localizing NSPredicateEditor</title><description>&lt;p&gt;Many people who know me personally (at least as a developer), know something interesting about me: I love &lt;code&gt;NSPredicate&lt;/code&gt;.  I love it so much that I stood up and &lt;a href="http://mactech.com/conference"&gt;blathered for an hour&lt;/a&gt; on how awesome it is.  I won&amp;#8217;t go into that here.&lt;/p&gt;

&lt;p&gt;One of the things that make &lt;code&gt;NSPredicate&lt;/code&gt; superbly awesome is the &lt;code&gt;NSPredicateEditor&lt;/code&gt;.  &lt;code&gt;NSPredicateEditor&lt;/code&gt;, in a nutshell, is a way to visually build an &lt;code&gt;NSPredicate&lt;/code&gt;, if you take the time to really dig in and understand what&amp;#8217;s going on.  Unfortunately that&amp;#8217;s somewhat difficult, since the documentation on &lt;code&gt;NSPredicateEditor&lt;/code&gt; is sparse, to say the least.&lt;/p&gt;

&lt;p&gt;Customizing &lt;code&gt;NSPredicateEditorRowTemplates&lt;/code&gt; is do-able, though you&amp;#8217;re going to spend a few hours of trial-and-error programming getting it to work properly.  However, if you want to localize the predicate editor, you are up a creek without a paddle.  There is absolutely &lt;em&gt;no&lt;/em&gt; documentation on it.&lt;/p&gt;

&lt;p&gt;So, here&amp;#8217;s a paddle.&lt;/p&gt;

&lt;p&gt;First off, some introduction: localizing an &lt;code&gt;NSPredicateEditor&lt;/code&gt; is a bit more complex than you would expect, because it works by displaying more-or-less natural-language phrases to the user.  Localizing buttons and labels is easy, because we deal with isolated words such as &amp;#8220;View file&amp;#8221; or &amp;#8220;Space used:&amp;#8221; and so on.  However, when you want to localize a whole sentence, suddenly you have to starting thinking about things like word order and the placement of prepositions in relation to nouns and verbs, and a whole host of other interesting challenges.&lt;/p&gt;

&lt;p&gt;To illustrate:  In English, when we meet someone new, we usually ask &amp;#8220;Where are you from?&amp;#8221;  To analyze just the order of words, we have:  Adverb verb pronoun preposition.  In Spanish, we would ask &amp;#8220;¿De donde es?&amp;#8221;.  Literally this means &amp;#8220;From where are you?&amp;#8221; (We could say this in English and people understand us, but it&amp;#8217;s uncommon).  In Spanish, the phrase is almost exactly backwards:  Preposition adverb verb (with implicit pronoun).  If we had a different view for displaying the adverb, and one for displaying the verb and pronoun, and one for displaying the preposition, then we would have to worry about rearranging our views to make the sentence readable.  Saying &amp;#8220;¿Donde es de?&amp;#8221; (Literally: Where are you from?) may make sense if we were to literally translate this to English, but to a native Spanish speaker, you&amp;#8217;re speaking nonsense.&lt;/p&gt;

&lt;p&gt;Unfortunately, this is the precise problem we face with &lt;code&gt;NSPredicateEditor&lt;/code&gt;.  In English we might say &amp;#8220;A is equal to B&amp;#8221;, but it&amp;#8217;s easy to imagine another language requiring something that&amp;#8217;s more like &amp;#8220;A and B are equal&amp;#8221;.&lt;/p&gt;

&lt;p&gt;To translate this discrepancy into &lt;code&gt;NSPredicate&lt;/code&gt;-speak, we have to deal with &amp;#8220;leftValue operation rightValue&amp;#8221; versus &amp;#8220;leftValue rightValue operation&amp;#8221;.&lt;/p&gt;

&lt;p&gt;Fortunately, there is a way to deal with this, and it relies on understanding three things:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;&lt;code&gt;NSLocalizedString()&lt;/code&gt; and friends. I&amp;#8217;m not going to cover this, since the documentation on how to localize is fairly straightforward&lt;/li&gt;
&lt;li&gt;&lt;code&gt;printf&lt;/code&gt;-style positional specifiers.  Here&amp;#8217;s a basic example of what these are:&lt;br/&gt;&lt;br/&gt;&lt;code&gt;NSLog(@"%2$@ %1$@", @"World", @"Hello");
//logs "Hello World"&lt;/code&gt;&lt;br/&gt;&lt;br/&gt;
The &amp;#8220;2$&amp;#8221; and &amp;#8220;1$&amp;#8221; in the format specifier simply mean &amp;#8220;use the second substitution value&amp;#8221; and &amp;#8220;use the first substitution value&amp;#8221; (respectively).  Easy.&lt;/li&gt;
&lt;li&gt;Using a special syntax for certain format specifiers (more on this later)&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Now that we understand this, we can get on with localizing our &lt;code&gt;NSPredicateEditor&lt;/code&gt;.  We understand that we need &lt;code&gt;NSLocalizedString()&lt;/code&gt; and that we can reposition substituted values using positional specifiers.  Now let&amp;#8217;s talk about the special format specifier syntax, in the context of another example.&lt;/p&gt;

&lt;p&gt;For simplicity, let&amp;#8217;s say we have an &lt;code&gt;NSPredicateEditor&lt;/code&gt; with three row templates:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;A compound row template ([Any, All, None] of the following are true)&lt;/li&gt;
&lt;li&gt;A string row template (property [is, is not, contains, begins with, ends with, like, matches] a user-entered-string)&lt;/li&gt;
&lt;li&gt;A selection row template (birthMonth is [January - December])&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;To properly localize these row templates, we simply need to produce some comments:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/**

NSLocalizedStringFromTable(@"%[Any, All, None]@ of the following are true", @"Predicate", @"localize the compound row template")
NSLocalizedStringFromTable(@"%[property]@ %[is, is not, contains, begins with, ends with, like, matches]@ %@", @"Predicate", @"localize the string row template")
NSLocalizedStringFromTable(@"%[birthMonth]@ %[is, is not]@ %[January, February, March, April, May, June, July, August, September, October, November, December]@", @"Predicate", @"localize the selection row template")

**/
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Some explanation about what&amp;#8217;s going on here:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Why are these in a comment?&lt;/strong&gt;&lt;br/&gt;Because we don&amp;#8217;t actually need this in the compiled code.  We just need it in the source code so that the &lt;code&gt;genstrings&lt;/code&gt; utility can find it.  We won&amp;#8217;t actually be using the &lt;code&gt;NSLocalizedString()&lt;/code&gt; macros in our final, compiled version.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;What&amp;#8217;s with the square brackets?&lt;/strong&gt;&lt;br/&gt;Because this is Objective-C, and we have to use square brackets everywhere, right?  RIGHT???&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;In reality, the square brackets are what makes the magic happen.  Each percent modifier (&lt;code&gt;%@&lt;/code&gt;) represents a single view on the row template UI.  Plain text (ex: &amp;#8220;of the following are true&amp;#8221;) is also represented as a view (specifically, an &lt;code&gt;NSTextField&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;For fields in a row template where you have multiple options, &lt;em&gt;those options are comma-delimited within the square brackets&lt;/em&gt;.  In the case of the compound row template, there are two fields: a popup that allows you to choose the kind of compound predicate (AND, OR, or NOT), and a field with some clarification text (&amp;#8220;of the following are true&amp;#8221;).  The options for the template must match &lt;em&gt;exactly&lt;/em&gt; (case, order, etc) as what you would see in the UI if you were to run your &lt;code&gt;NSPredicateEditor&lt;/code&gt; without localization.  If you mistype something, or mis-capitalize something else, that translation will not work.&lt;/p&gt;

&lt;p&gt;Notice also that some fields don&amp;#8217;t have anything to translate.  The second row template shows &amp;#8220;property&amp;#8221;, some various string operators, and then &lt;code&gt;%@&lt;/code&gt;.  The &lt;code&gt;%@&lt;/code&gt; indicates that this will be replaced with something that cannot be translated.  In this case, it would be an &lt;code&gt;NSTextField&lt;/code&gt;, since we&amp;#8217;re expecting the user to use this to enter some text.&lt;/p&gt;

&lt;p&gt;When we run this code through the &lt;code&gt;genstrings&lt;/code&gt; utility, we will get a file created (&amp;#8220;Predicate.strings&amp;#8221;) that contains this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;/* localize the compound row template */
"%[Any]@ of the following are true" = "%[Any]@ of the following are true";
"%[All]@ of the following are true" = "%[All]@ of the following are true";
"%[None]@ of the following are true" = "%[None]@ of the following are true";

/* localize the selection row template */
"%[birthMonth]@ %[is]@ %[January]@" = "%1$[birthMonth]@ %2$[is]@ %3$[January]@";
"%[birthMonth]@ %[is]@ %[February]@" = "%1$[birthMonth]@ %2$[is]@ %3$[February]@";
"%[birthMonth]@ %[is]@ %[March]@" = "%1$[birthMonth]@ %2$[is]@ %3$[March]@";
"%[birthMonth]@ %[is]@ %[April]@" = "%1$[birthMonth]@ %2$[is]@ %3$[April]@";
"%[birthMonth]@ %[is]@ %[May]@" = "%1$[birthMonth]@ %2$[is]@ %3$[May]@";
"%[birthMonth]@ %[is]@ %[June]@" = "%1$[birthMonth]@ %2$[is]@ %3$[June]@";
"%[birthMonth]@ %[is]@ %[July]@" = "%1$[birthMonth]@ %2$[is]@ %3$[July]@";
"%[birthMonth]@ %[is]@ %[August]@" = "%1$[birthMonth]@ %2$[is]@ %3$[August]@";
"%[birthMonth]@ %[is]@ %[September]@" = "%1$[birthMonth]@ %2$[is]@ %3$[September]@";
"%[birthMonth]@ %[is]@ %[October]@" = "%1$[birthMonth]@ %2$[is]@ %3$[October]@";
"%[birthMonth]@ %[is]@ %[November]@" = "%1$[birthMonth]@ %2$[is]@ %3$[November]@";
"%[birthMonth]@ %[is]@ %[December]@" = "%1$[birthMonth]@ %2$[is]@ %3$[December]@";
"%[birthMonth]@ %[is not]@ %[January]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[January]@";
"%[birthMonth]@ %[is not]@ %[February]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[February]@";
"%[birthMonth]@ %[is not]@ %[March]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[March]@";
"%[birthMonth]@ %[is not]@ %[April]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[April]@";
"%[birthMonth]@ %[is not]@ %[May]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[May]@";
"%[birthMonth]@ %[is not]@ %[June]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[June]@";
"%[birthMonth]@ %[is not]@ %[July]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[July]@";
"%[birthMonth]@ %[is not]@ %[August]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[August]@";
"%[birthMonth]@ %[is not]@ %[September]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[September]@";
"%[birthMonth]@ %[is not]@ %[October]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[October]@";
"%[birthMonth]@ %[is not]@ %[November]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[November]@";
"%[birthMonth]@ %[is not]@ %[December]@" = "%1$[birthMonth]@ %2$[is not]@ %3$[December]@";

/* localize the string row template */
"%[property]@ %[is]@ %@" = "%1$[property]@ %2$[is]@ %3$@";
"%[property]@ %[is not]@ %@" = "%1$[property]@ %2$[is not]@ %3$@";
"%[property]@ %[contains]@ %@" = "%1$[property]@ %2$[contains]@ %3$@";
"%[property]@ %[begins with]@ %@" = "%1$[property]@ %2$[begins with]@ %3$@";
"%[property]@ %[ends with]@ %@" = "%1$[property]@ %2$[ends with]@ %3$@";
"%[property]@ %[like]@ %@" = "%1$[property]@ %2$[like]@ %3$@";
"%[property]@ %[matches]@ %@" = "%1$[property]@ %2$[matches]@ %3$@";
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Man, that&amp;#8217;s a lot of stuff to localize!  If you look closely, you can see that every occurrence of &lt;code&gt;NSLocalizedString&lt;/code&gt; has been expanded &lt;em&gt;for all possible combinations&lt;/em&gt;.  So if you have a row template that supports 3 different left expressions, 6 different operators, and 7 different right expressions, then you have to translate 126 different things (3 * 6 * 7 = 126).&lt;/p&gt;

&lt;p&gt;One thing that &lt;code&gt;genstrings&lt;/code&gt; has conveniently done for us is insert positional specifiers!  This allows us to rearrange the order of the string in a translated version, but still get the appropriate value substituted in.&lt;/p&gt;

&lt;p&gt;Now that we have this &lt;code&gt;.strings&lt;/code&gt; file, we can translate it just like any other strings file, and we can also rearrange fields as necessary:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;"%[Any]@ of the following are true" = "%[Cualquiera]@ de las siguientes son verdaderas";
"%[All]@ of the following are true" = "%[Todas]@ de las siguientes son verdaderas";
"%[None]@ of the following are true" = "%[Ningún]@ de las siguientes son verdaderas";

...

"%[property]@ %[is]@ %@" = "%1$[propiedad]@ y %3$@ %2$[son iguales]@"; //literally "property and [value] are equal"
"%[property]@ %[is not]@ %@" = "%1$[propiedad]@ y %3$@ %2$[no son iguales]@";
"%[property]@ %[contains]@ %@" = "%1$[propiedad]@ %2$[contiene]@ %3$@";

...
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The final step (beyond including the translated strings files as resources in your application) is that you need to tell your &lt;code&gt;NSPredicateEditor&lt;/code&gt; where to find this information.  There are two ways to do this:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;-[NSPredicateEditor setFormattingStringsFilename:]&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;-[NSPredicateEditor setFormattingDictionary:]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;The first option is usually the way to go.  You simply give it the name of your &lt;code&gt;.strings&lt;/code&gt; file sans extension (in this case, &lt;code&gt;@"Predicate"&lt;/code&gt;) and you&amp;#8217;re good to go.  If it comes across a syntax error, it&amp;#8217;ll log it so you can debug it.  The problem with this approach is that it only looks inside &lt;code&gt;[NSBundle mainBundle]&lt;/code&gt; for the resource.  So if you&amp;#8217;re writing a plugin (such as a system preference pane), this won&amp;#8217;t work.&lt;/p&gt;

&lt;p&gt;Fortunately, there&amp;#8217;s the second option, and it works like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;NSString * stringsFile = [[NSBundle bundleForClass:[self class]] pathForResource:@"Predicate" ofType:@"strings"];
NSString * strings = [NSString stringWithContentsOfFile:stringsFile encoding:NSUTF16StringEncoding error:nil];
NSDictionary * formattingDictionary = [strings propertyListFromStringsFileFormat];
[predicateEditor setFormattingDictionary:formattingDictionary];
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is pretty straightforward: load the strings file into memory, use a built-in method to convert it to an &lt;code&gt;NSDictionary&lt;/code&gt;, and then give that dictionary to the predicate editor.&lt;/p&gt;

&lt;p&gt;So there you have it!  An actual explanation on how to localize an &lt;code&gt;NSPredicateEditor&lt;/code&gt;!  Hopefully anyone who comes across this will find it useful, since it was a total pain to figure out. :)&lt;/p&gt;

&lt;p&gt;Enjoy!&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1482915398</link><guid>http://funwithobjc.tumblr.com/post/1482915398</guid><pubDate>Thu, 04 Nov 2010 16:13:00 -0700</pubDate><category>nspredicateeditor</category><category>localization</category></item><item><title>Method Swizzling</title><description>&lt;p&gt;Recently I wrote about how to dynamically subclass objects in Objective-C, and when that might be useful.&lt;/p&gt;

&lt;p&gt;While dynamic subclassing can be really useful, there is one major gotcha that can make it not very effective, and that was hinted at the end of my post:  Key-Value Observing.&lt;/p&gt;

&lt;p&gt;When you add an observer to an object, the KVO mechanism will dynamically subclass that object to implement the observation logic.  For example, consider the following class:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@interface DataObject : NSObject

@property NSInteger dataValue;

@end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When you observe an instance of &lt;code&gt;DataObject&amp;lt;&lt;/code&gt;, a dynamic subclass is created.  This class is called &lt;code&gt;NSKVONotifying_DataObject&lt;/code&gt;, but even that is hidden from you.  The KVO subclass is devious; it hides its existence.  Consider this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;DataObject * dataObject = [[DataObject alloc] init];

[dataObject addObserver:self forKeyPath:@"dataValue" options:0 context:NULL];

NSLog(@"%@", [dataObject class]);  //logs "DataObject"
NSLog(@"%@", object_getClass(dataObject));  //logs "NSKVONotifying_DataObject"
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;In other words, the class of an observed object does everything it can to look and behave exactly like the original class.  For the most part, this is appropriate behavior.  However, when you want to implement your own dynamic subclassing mechanism, it can wreak havoc.  A dynamic KVO subclass does not like to be subclassed, because when you remove all the observers from the object, the class of the object is changed back to its original class.  This means that even if you manage to dynamically subclass a KVO class, those changes will be lost when the class of the object is changed back to its original class.&lt;/p&gt;

&lt;p&gt;So in the case of &lt;a href="http://github.com/davedelong/CHLayoutManager"&gt;CHLayoutManager&lt;/a&gt;, a different mechanism for automatic cleanup was needed, since it is not uncommon to observe a UI element in order to react to state changes.&lt;/p&gt;

&lt;p&gt;After some experimentation, I came up with an alternative: replace the &lt;code&gt;-dealloc&lt;/code&gt; method of &lt;code&gt;NSView&lt;/code&gt; with a new version.&lt;/p&gt;

&lt;p&gt;Now, I don&amp;#8217;t have the source to AppKit.  I don&amp;#8217;t know what &lt;code&gt;NSView&lt;/code&gt; is doing under the hood.  Fortunately, with Objective-C, that&amp;#8217;s not really a problem, because there&amp;#8217;s this really neat function in the runtime called &lt;code&gt;method_exchangeImplementations&lt;/code&gt;, and it works like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;+ (void) initialize {
  if (self == [CHLayoutManager class]) {
    Class nsview = [NSView class];

    SEL dynamicDealloc = @selector(chlayoutautoremove_dynamicDealloc);

    Method newDealloc = class_getInstanceMethod(self, dynamicDealloc);
    if (newDealloc != NULL) {
      class_addMethod(nsview, dynamicDealloc, method_getImplementation(newDealloc), method_getTypeEncoding(newDealloc));
      newDealloc = class_getInstanceMethod(nsview, dynamicDealloc);

      if (newDealloc != NULL) {
        Method originalDealloc = class_getInstanceMethod(nsview, @selector(dealloc));
        method_exchangeImplementations(originalDealloc, newDealloc);
      }
    }
  }
}

- (void) chlayoutautoremove_dynamicDealloc {
  if ([self isKindOfClass:[NSView class]]) { //to prevent people from being stupid
    [[CHLayoutManager sharedLayoutManager] removeConstraintsFromView:(NSView *)self];
    [[CHLayoutManager sharedLayoutManager] setLayoutName:nil forView:(NSView *)self];
    //THIS IS NOT A RECURSIVE CALL
    [self chlayoutautoremove_dynamicDealloc];
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a two step process:&lt;/p&gt;

&lt;p&gt;First, we find the &lt;code&gt;NSView&lt;/code&gt; class and add a new method to it.  This method, called &lt;code&gt;-chlayoutautoremove_dynamicDealloc&lt;/code&gt; simply performs cleanup with the layout manager singleton.  After we add the method to &lt;code&gt;NSView&lt;/code&gt;, we swap the implementations of &lt;code&gt;-dealloc&lt;/code&gt; and &lt;code&gt;-chlayoutautoremove_dynamicDealloc&lt;/code&gt;.  This means that &lt;code&gt;-[NSView dealloc]&lt;/code&gt; will invoke the implementation of &lt;code&gt;-chlayoutautoremove_dynamicDealloc&lt;/code&gt;, and &lt;code&gt;-[NSView chlayoutautoremove_dynamicDealloc]&lt;/code&gt; will invoke the original &lt;code&gt;-dealloc&lt;/code&gt; code.  Essentially, this is more or less injecting code into &lt;code&gt;NSView&lt;/code&gt; that will be executed right before the &lt;code&gt;-dealloc&lt;/code&gt; code gets executed.&lt;/p&gt;

&lt;p&gt;Neat!&lt;/p&gt;</description><link>http://funwithobjc.tumblr.com/post/1482839994</link><guid>http://funwithobjc.tumblr.com/post/1482839994</guid><pubDate>Sat, 23 Oct 2010 14:15:59 -0700</pubDate><category>runtime</category></item></channel></rss>
