Archive for the ‘Programming’ Category

A subtlety of object identity in Obj-C


2010
02.26

A problem: given an object a of class A that aggregates a publicly accessible instance of class B determine if an instance changed by polling periodically. This comes up often in concurrent systems where an object change warrants a response while KVO is undesirable. The first thought that comes to mind is to a cache the instance of B during each cycle of polling after the comparison of the cached instance to the present value.

Our code might look like this

if (cachedB != [a valueOfB]) { triggerEvent(...); }
cachedB = [a valueOfB];

Unfortunately this fails miserable due to the fact that a newly allocated instance of B may occupy the same memory location as the previous one (assuming, of course, that we never retain the cached value). This is a low probability failure and is extremely hard to debug. This bug is solved by storing a timestamp upon change of instance of B inside a, and cacheing it instead of the memory address.

Modifying dynamic linker paths


2009
05.20

There times when standard locations for libraries and frameworks just don’t cut it. For such times a lineup of environment variables can be used to guide the linker. Typing

man dyld

in the terminal tells the story. Also

otool -L <executable-name>

lists library locations for a given executable.

Building CGAL 3.3.1 on (10.5) Leopard


2009
04.29


Not an exercise for the faint of heart. In fact this applies to using it in your programs as well. While I managed to build the libs, I never managed to build the demos that rely on Qt.
 

  • Download the mac distribution from CGAL portal.
  • Prior to installing CGAL you need to have a few prerequisites on your system: boost, GMP, MPFR, Qt (3 didn’t manage to get it working with 4)
  • It is easiest to use macports to get these. After downloading and installing macports install the libraries as follows
    sudo port install boost
    sudo port install GMP
    sudo port install MPFR
    sudo port install qt3-mac
  • You may also wish to install qt4 by invoking
    sudo port install qt4-mac-devel
  • Open your terminal window and cd to CGAL home directory
  • Copy (rename) boost program_options library file so the installer picks it up by going into /opt/local/lib and type
    cp libboost_program_options-mt.a libboost_program_options.a
  • Invoke ./instal_cgal -i to enter interactive mode of their installer
  • Provide the paths the installer cannot find automatically (they are all in /opt/local/include and /opt/local/lib)
  • Before building examples (from examples directory invoke make) don’t forget to set an environment varible
    export CGAL_MAKEFILE=<path_to_CGAL-3.3.1>/make/makefile_i386_Darwin-9.6_g++-4.0.1
  •  

     

    SymbicLogKit 0.6 (Beta)


    2009
    02.20

    At last releasing SymbicLogKit. The kit is a simple logging/tracing framework polarized toward desktop (vs. server) development; an itch I’ve needed to scratch for quiet some time. I can already hear a poignant skeptic say that printf and NSLog do the job just fine, and that availability of other solutions such as Log4Coocoa and ASL (Apple System Logging) adds the insult to an injury.

    I was not entirely happy with the existing solutions and the following points and decided to build my own framework.

    • Tracing/logging/debugging code often serves a purpose long after its initial purpose, so it shouldn’t be removed much of the time following a debugging session. Instead logging code should be well thought out as to provide a developer with useful info in the future.
    • If the above statement is accepted then we need a means of selectively blocking/enabling tracing code based on origin, level, thread, and other parameters. Without the ability to select what gets through we’ll simply get lost in the overly verbose output.
    • Enabling/disabling parts of output should be snappy and should be done at runtime.
    • A developer may want to do more useful things than printf with tracing output, so the output should be structured.
    • The framework should be UI centric, nice to look at, and should be easy to include and take advantage of in desktop applications.

    The core of the framework is a singleton class called SYLogger. The instance of this class allows a user to add objects conforming to SYLoggerChannel protocol. Such objects are essentially output channels for a logger instance. There are two such objects provided by the framework: SYConsoleView and NSLoggingChannel.

    SYConsoleView is an NSView that can be embedded into your application much the same way as any NSView subclass. The view is a tabular console for your output. On the other hand NSLoggingChannel is a simplistic channel that forwards your output to NSLog(...) call having formatted it nicely.

    In order to make use of the framework the channels must be added to SYLogger instance. Messages are sent to the logger by invoking one of the following macros. There are 4 debugging levels defined at the moment (Debug, Info, Warning, Error) each assigning an immediacy level to a message. The variadic macros take NSString*s as parameters, the first being a format string (think [NSString stringWithFormat:...]).

    #define elog(str, ...)
    #define elogDebug(str, ...)
    #define elogInfo(str, ...)
    #define elogWarn(str, ...)
    #define elogError(str, ...)

    There’s also an SYConfiguratorView which enables a user (a developer typically) to configure the logger. By configure I mean to provide a list of class-selector-level tripples describing which output should be blocked. The control is nothing more than a table with the first column hosting an ICU regular expression for class-name, the second hosting an ICU regular expression for selector-name (e.g. “dictionaryWithObjects:forKeys:count:”, “array”, etc.).

    The above screenshot, for example, represents a configuration that blocks output from within drawRect: selectors of all classes whose names end in “View” as well as from all selectors whose name begins in “run” irrespective of a class they belong to.

    Atomic operations are your friends


    2009
    02.20

    I often come across multithreaded codes that work 99.9% of the time but share a common flaw. They exhibit unrepeatable behavior on occasion because such codes treat assignment as an atomic operation.

    This assumption is fundamentally flawed since assignment such as  int64_t a=b; may take 2 or ore CPU instructions to complete. For instance, in the case of a 64-bit integer assignment could execute inside two instructions; one for low- and high-word of the register. The instruction bipole could in theory (and does in practice) get interrupted by other threads. Such bugs are extremely difficult to track and isolate since assignment is indeed atomic for most cardinal datatypes in C/C++ but isn’t required to be. To appreciate the complexity multithreading gives rise to especially when multiple cores/CPUs are involved read this article.

    Many of my fellow developers could save themselves from glib frustrations of caffeine charged moonwalks through late-night debugging sessions by being more conscious of non-atomicity of assignment. In fact, an added benefit is that an understanding these facilities often eliminates the need for synchronization primitives in a number of situations consequently making codes faster and easier to follow.

    The facilities are a part of Kernel framework and can be conveniently imported in ObjC as follows:

    #import <libkern/OSAtomic.h>

    I should point out that atomicity of (at least assignment) could also be achieved through the use of ObjC 2.0 properties which are atomic by default. However, the sweet of OSAtomic-operations is reacher and eliminates the need for overzealous property syntax.

    There are however a few quirks requiring our attention if we are to make use of the API. OSAtomicXXX calls require their arguments to be aligned at natural boundaries in memory. Specifically, 32-bit variables must be aligned at 4 byte boundaries and 64-bit ones at 8 byte boundaries. The easiest way to insure that such alignment takes place in g++ compiled code is to use a proprietary extension. Also don’t forget to declare them volatile since a compiler may not warn you if you omit volatile from declaration. The following code demonstrates how one may declare instance variables for use in OSAtomicXXX calls.

    typedef volatile int64_t vint64;

    @interface MyObject : NSObject
    {
    vint32 shouldContinue __attribute__ ((aligned (4)));
    vint32 didFinish __attribute__ ((aligned (4)));
    vint64 haveDataToReload __attribute__ ((aligned (8)));
    }
    @end

    Implicit type conversion caveats in C/C++


    2009
    02.11

    Even experienced developers fall victims to type conversion intricacies in C. Consider the following snippet.

    unsigned a=7;
    int32_t b=-55;
    std::cout << (a+b) << std::endl;

    Running these lines produces console output of 4294967248 which certainly isn’t an expected result of the sum. The “paradox” is a result of how implicit type conversion works in C++. The standard interpretation of unsigned (at least in most compilers) is a 32-bit unsigned integer. When a signed and an unsigned integers of the same size are added together the compiler implicitly treats the result as unsigned. Thus the output.

    However let us experiment with variables of different sizes as in the following example and this time we spell out their sizes to avoid any confusion.

    uint32_t a=7;
    int64_t b=-55;
    std::cout << (a+b) << std::endl;

    It may be a shock to some of us that this snippet spits out the expected -48. Here size of the larger variable takes precedence over signedness.

    An NSValueTransformer example


    2009
    01.27

    NSValueTransformers can be extremely useful, especially when one wishes to make heavy use of bindings in Interface Builder. This facility is typically used to modify values displayed by a control in a declarative way. The following example illustrates a simple NSValueTransformer subclass that does nothing more than chops away a file extension from a string.

    @interface QCChopAwayExtensionValueTransformer: NSValueTransformer {}
    @end

    @implementation QCChopAwayExtensionValueTransformer
    + (Class)transformedValueClass { return [NSString class]; }
    + (BOOL)allowsReverseTransformation { return NO; }
    - (id)transformedValue:(id)value {
        if (value == nil) return nil;
        return [value stringByDeletingPathExtension];
    }

    +(void) initialize
    {
        NSString *name = @"QCChopAwayExtensionValueTransformer";
        [[NSValueTransformer class] setValueTransformer:[self new]
                                    forName:name];
    }

    @end

    In order to make use of the subclass in IB it needs to be registered by name with the system as is done in the above code example. Once registered a transformer can be used inside, say, a table column as shown below.

    Using NSValueTransformer

    Better IB outlets in Objective-C 2.0


    2008
    12.15

    Apple docs lack clarity when it comes to whether IBOutlets retain objects they point to. However a new way to specify outlets in Obj-C 2.0 saves the day.

    @interface MyController : NSObject
    {
        NSTextField* _text;
    }
    @property (readwrite, retain) IBOutlet NSTextField* text;
    @end

    @implementation MyController
        @synthesize text=_text;
    @end

    This mechanism allows a developer to control retention behavior association with an outlet. Why should you care? The story with loading a nib (xib) file is that top-level objects are returned retained and it is left up to a developer to release them when they are no longer needed. Misunderstanding of this detail results in numerous leaks across applications.

    A way to avoid tracking the top-level objects is to structure nibs so that every top-level object is reachable from the “File’s Owner” and to release top-level objects upon loading. However, this strategy brings about sad results unless one ensures that IBOutlets are always retained.

    A nifty Silicon Valley style interview question


    2008
    12.08

    It goes like this… Please write a function that converts a string containing a positive integer into an int. Basically write an atoi function. There are a couple of restrictions: you must use only one loop and can’t use any data structures other than an input array.

    Here is a sample implementation

    int atoi(char * str)
    {    
        int incr = 1;
        int res = 0;

        int p=1;
        for (int j=0; j>=0; j+=incr)
        {
            if (str[j]=='\0')
            {            
                incr = -1;
            }
           
            if (incr < 0 && str[j] != '\0')
            {
                res += p * (str[j]-'0');
                p*=10;
            }
        }

        return res;
    }