The Elegant Chaos Blog

November 22, 2011

Ambientweet 1.0.1 is out!

This version has a whole raft of improvements, including:

  • Reduced the frequency of refreshes, to avoid running over the Twitter call limit.
  • Post windows now use the same style as the main tweet window.
  • The length of posts is now calculated intelligently to account for link shortening. So if you paste in a long link, it won’t use up all of your character count, as the link will be shortened in the actual post.
  • Auto-completion list for @users in post window now includes all users that the app has encountered.
  • Now correctly restores cached tweets and users when loading.
  • Added subtle gradient to window backgrounds.
  • Fixed beta Sparkle feed URL (the app was looking at the non-beta feed instead).
  • Updated the manual with screenshots of new posting UI.
  • Fixed window resizing.
  • Improved sorting, refreshing with new items.
  • Changed user guide code to be sandbox-friendly (copies guide into the Caches folder and opens it from there).

There are lots more improvements and new features on the way in a future version, please give 1.0.1 a try!

more...

November 21, 2011

During a recent submission I came across a problem.

I got an automatically generated email back from Apple with this sort of thing in it:

Invalid Signature - the nested app bundle ECFoundation 
(Ambientweet.app/Contents/Frameworks/ECFoundation.framework)
is not signed, the signature is invalid, or it is not signed with an Apple submission certificate. 
Refer to the Code Signing and Application Sandboxing Guide for more information.

It’s a bit annoying that the email is capable of spotting that I have one of three possible problems, but not narrowing the actual cause down for me. It’s also a bit annoying that this only runs when you’ve submitted, and not when you verify an application with Xcode.

Be that as it may… … the main point is that it looks like Apple are starting to require that all code inside your application bundle is signed. This includes any frameworks or plugins you’ve embedded, even if you didn’t actually build them.

I’m slightly mystified as to why Xcode doesn’t do this for you at the point when you submit - since it asks you for an indentity to use, and presumably does some re-signing with it at this point.

However, as luck would have it, it’s fairly easy to write a script to do what we need.

for f in "${CODESIGNING_FOLDER_PATH}/Contents/PlugIns/"*
do
    BUNDLEID=`/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$f/Contents/Info.plist"`
    codesign -f -i ${BUNDLEID} -vv -s "${CODE_SIGN_IDENTITY}" "$f"
done
 
for f in "${CODESIGNING_FOLDER_PATH}/Contents/Frameworks/"*
do
    BUNDLEID=`/usr/libexec/PlistBuddy -c "Print :CFBundleIdentifier" "$f/Resources/Info.plist"`
    codesign -f -i ${BUNDLEID} -vv -s "${CODE_SIGN_IDENTITY}" "$f"
done

This script goes through the build app’s PlugIns and Frameworks folders and signs everything it finds. It uses the application bundle id from each framework/plugin when signing. From one reading of the signing instructions, it sounded like everything bundled in with your app has to have the same bundle id, so this might not be quite the right approach - the script might need to take the bundle id from the app, sets the bundle id of each embedded framework to it, and then signs the framework.

However, apps submitted after building with this script don’t seem to generate the warnings, so for now this one seems to do the job.

I’m running the script with a final Run Script build phase in the target for my main application. This means that the bundles and plugins inside the app will always get signed, whatever configuration I choose.

Alternatively, you could probably run it as a post-action script in the Archive part of your build scheme, so that the extra signing only gets done when you’re about to submit. Actually I think that’s probably more in line with Apple’s advice, which seems to be not to sign things until you’re actually submitting them, so as not to give legitimacy to development builds which accidentally escape into the wild. However, I’m not certain that all the environment variables that I’m using will be set at that point, so it may be that the script would need modifying. I’ll leave that bit as an exercise for the reader…

more...

November 16, 2011

A while ago I blogged about how I’d really like Objective-C to have built in support for lazy properties.

My ideal solution would be something like this:

@property (nonatomic, retain, lazy) NSString* name;

The synthesized getter for this property would automatically call a method

 - (NSString*)nameInit 

when the property was first accessed, and would use the resultant value to initialise the property.

This has some advantages over any hand-rolled solution:

  • it can remain efficient
  • it can support the retain/copy semantics and atomicity of the property
  • it avoids the need for boiler-plate code for every property to test if it needs to be initialised

In the absence of this solution in the language, I offered a rather complicated set of macros to attempt to implement something similar.

Since then I’ve thought about it a bit more, and come up with another couple of ways of tackling the same task… What Do We Want To Do? ———————-

Let’s say we’ve got a class:

@interface MyClass : NSObject

@property (nonatomic, retain) NSString* name;

@end

and we want to make the name property lazy.

What we need to do is to somehow insert some checking code into the -(NSString*)name getter function, that does something like this:

id value = self.name; // <-- this is a call to the ‘original’ getter
if (!value)
{
    value = [self nameInit];
    self.name = value;
}

return value;

Note that we need to be able to call the original getter here. We could attempt to access the underlying ivar directly, but using the original getter is much better as it preserves the property semantics regarding retain, copy etc.

Using Inheritance

One clean way to do this would be to insert a class in-front of our class, and implement our modified getter there. That allows us to cleanly call on to the original getter.

So we end up with something like this in our header file:

@interface MyClass : NSObject

@property (nonatomic, retain) NSString* name;

@end

@interface MyClassLazy : MyClass
@end

And this in our implementation file:

@implementation MyClass
@synthesize name;
// normal implementation here

// lazy initialisation function for name property
- (NSString*)nameInit
{
    return @"blah";
}
@end


@implementation MyClassLazy

- (NSString*)name
{
    id value = [super name];
    if (!value)
    {
        value = [self nameInit];
        self.name = value;
    }

    return value;
}

@end

Getting Things The Right Way Round

That’s quite neat, but there’s a problem. Our class is called MyClass, but in order to get the lazy behaviour, we need to use the class called MyClassLazy.

We can fix this with a bit of renaming. The header now looks like

@interface MyClassNonLazy : NSObject

@property (nonatomic, retain) NSString* name;

@end

@interface MyClass : MyClassNonLazy
@end

And the implementation:

@implementation MyClass
@synthesize name;
// normal implementation here

// lazy initialisation function for name property
- (NSString*)nameInit
{
    return @"blah";
}
@end


@implementation MyClass

- (NSString*)name
{
    id value = [super name];
    if (!value)
    {
        value = [self nameInit];
        self.name = value;
    }

    return value;
}

@end

Wrapping It Up Nicely

So that, in a nutshell, is a solution that works. With a bit of judicious macro definition, we can generalise this:

#define lazy_interface(class,parent) interface class##_nonlazy : parent
#define end_lazy_interface(class) end @interface class : class##_nonlazy @end

#define lazy_implementation(class) implementation class##_nonlazy
#define lazy_properties(class) end @implementation class
#define end_lazy_implementation(class) end

#define lazy_synthesize(prop) \
    class Dummy__; \
    - (NSString*)prop \
    { \
    id value = [super prop]; \
    if (!value) \
    { \
    value = [super prop##Init]; \
    self.test = value; \
    } \
    \
    return value; \
    }

So now, we can do this in the header:

@lazy_interface(TestClass, NSObject)

@property (nonatomic, retain) NSString* name;

@end_lazy_interface(TestClass)

And this in the implementation:

@lazy_implementation(TestClass)

@synthesize name;

// lazy initialisation function for name property
- (NSString*) nameInit
{
    return @"blah";
}

@lazy_properties(TestClass)

@lazy_synthesize(name)

@end_lazy_implementation(TestClass)

Can We Do Better?

Which is kind of nifty, but still, well, ugly. All our nasty macros make it not look like normal Objective-C.

So how about a different approach? Tune in to my next post

more...

In my previous post I presented a way to implement lazy properties.

It was a bit macro-heavy though, and looked kind of messy. I wondered if there was another way. Objective C is marvellously dynamic and introspective. Shouldn’t we be able to do something clever at runtime to achieve what we want?

In a word, the answer is yes, we can… Let’s say we adopt a standard pattern for the initialisation methods for any lazy properties, like we did in the previous implementation:

 <prop>Init.

So for a property called name, the initialisation method would be called

nameInit

At class initialisation time, we can use Objective-C’s introspection routines to run through a list of all our class’s properties, looking for ones that have a lazy initialisation method.

For those that we find, we can swap out the normal implementation of the getter method for one which calls on to the original getter to get the current value, initialises it if the getter returned nil, then returns the value.

That sounds neat, but we will need to define a slightly different getter method for each property - since they all have to call on to a different original getter. Where are we going to put this code?

The answer turns out to be simple - we put it in the lazy initialisation method that we use to indicate that the property is lazy! So not only does the presence of the method tell us that it’s a lazy property, but the body of the method actually performs the lazy get.

Implementing The Replacement Getter Method

Each of these new getter / lazy-initialisation methods is going to look pretty much the same - call the original getter, check the value, initialise if necessary, return the value. Most of the code is boilerplate, but the getter method that we need to call onto changes for each property.

We could probably do something clever here to work out the name of this property at runtime by performing some selector to string conversions, but we’d have to do it every single time the getter was called. As we don’t want the performance to totally suck, it would be good if we could just make a normal call to the original method, check the returned value, and only do potentially slow and clever things on the one occasion when we need to do some initialisation. We can achieve this quite easily with a macro that expands to a few lines of code for every lazy getter.

So what do we end up with?

The interface for our lazy class looks like this:

@interface TestClass : NSObject

@property (nonatomic, retain) NSString* test;

@end

Ok, that’s… erm… pretty normal!

The implementation looks like this:

@implementation TestClass

@synthesize test;

+ (void)initialize
{
    if (self == [TestClass class])
    {
        [self initializeLazyProperties];
    }
}

@lazy_synthesize(test, @"test value"); 

@end

That’s also pretty normal!

We only have two odd things going on here. First, we need to perform a one off initialisation when the class is first loaded, to hook up all the magic.

We can do this in the +initialize method of the class. We could make this step even briefer with a macro, but in this case I figured that it was cleaner to just put the code in.

The second thing we’re doing is “synthesizing” the lazy getter. We could easily just put in the actual boiler plate code each time, but since writing boiler-plate is really what we’re trying to get away from, a macro makes sense.

This solution is much cleaner, and it works. In my next post I’ll show you the implementation.

more...

In my previous post I showed a relatively clean way to implement lazy properties generically using the dynamic runtime.

So how does this dynamic implementation actually work? The interface is pretty small:

@interface NSObject(ECLazyProperties)

+ (void)initializeLazyProperties;

#define lazy_synthesize(name,init) \
class Dummy__; \
- (id)name##Init__ \
{ \
id value = [self name##Init__]; \
if (!value) \
{ \
    value = (init); \
    [self setValue:value forKey:@#name]; \
} \
return value; \
}

#define lazy_synthesize_method(name,method) lazy_synthesize_value(name,[self method])

@end

Most of the work here is in one macro.

Essentially what this does is define a lazy initialisation method for a property. The method:

  • calls on to the original property getter
  • if it’s got a value, we just return it
  • if not, we first KVC to update the original property with its initial value

We define the name of the method by appending Init__ to the property name. We could have appended just Init, but this method really shouldn’t be called publicly, so I went for a slightly more obscure name.

How it calls the original getter is kind of interesting. If you unpick the macro you’ll see that it appears to be calling itself. Isn’t this going to lead to some hideous recursion?

The answer is no - because the method will have been swizzled. When we’re actually running in the method, it will be as a result of a call to the original getter method. So if we want to call the original getter method, we need to actually call the init method instead!

If we do discover that the value is uninitialised, we then use KVC to call the proper setter with an initial value.

So all of this relies on some swizzling. How do we set that up?

The implementation of initializeLazyProperties looks like this:

+ (void)initializeLazyProperties
{
    uint count;
    objc_property_t* properties = class_copyPropertyList(self, &count);
    for (int i = 0; i < count ; i++)
    {
        const char* propertyName = property_getName(properties[i]);
        SEL init = NSSelectorFromString([NSString stringWithFormat:@"%sInit__", propertyName]);
        if ([self instancesRespondToSelector:init])
        {
            SEL getter = NSSelectorFromString([NSString stringWithFormat:@"%s", propertyName]);
            Method initMethod = class_getInstanceMethod(self, init);
            Method getterMethod = class_getInstanceMethod(self, getter);
            
            method_exchangeImplementations(initMethod, getterMethod);
        }
    }
    free(properties);
}

We iterate through a list of properties, looking to see if there is a corresponding lazy initialise method for it. If there is, we simply swizzle the original getter method with the init method.

When the user calls the getter, they’ll actually get the init method. This will call on to the getter, check the value, and initialise if necessary.

Complex Initialisation

In the example, we’re just supplying a fixed initial value, but of course the real point of lazy initialisation is for situations where we need to do something time consuming in the initialisation, and we only want to actually do it if we have to.

For this situation you can use the second macro - lazy_synthesize_method. Instead of passing in an initial value, you pass in a method to call to return the value.

Conclusions

This code seems to actually work, but I’ve not tested it intensively to see whether it behaves property in all situations - for example with KVC/KVO.

I think it should do, but right now I view it largely as a thought experiment.

Right back at the beginning I said that the way I really think it should work is

@property (nonatomic, retain, lazy) NSString* name;

I still think that would be ideal. I think that what I’ve done illustrates that it ought to be entirely possible to add a hack to Clang to implement this, but I leave that as an exercise for the reader…

If anyone is interested in the full source code to my implementation, you’ll find it in the ECCore module of my open source ECFoundation library.

[Updated Feb 2012 to fix some broken links]

more...