2015-07-26

JSTalk script for Acorn, crunching images for iOS

So it was time to crunch images for inclusion in an iOS app again. Because I ditched GIMP and moved to Acorn, I can't reuse my old Scheme script.

I had to use JSTalk instead. It is by the same dude that wrote Acorn. It is basically a JavaScript wrapper to Core Foundation.

I decided on JSTalk over AppleScript after glancing at the AppleScript syntax for about 5 seconds. I heard about JSTalk from the Acorn scripting docs.

Anyway, I had finished editing my "@2" images manually, and I needed the half-size image files. I had them all in one directory.

I ran this script straight from the JSTalk Editor.

var acorn = JSTalk.application("Acorn");
var dirPath = @"/Users/jeff/VGT/art/vegetable photos/Working Temp/";
var fileManager = [[NSFileManager alloc] init];
var dirEnum = [fileManager enumeratorAtPath:dirPath];
var fileName = [dirEnum nextObject];

while (fileName) {
    NSLog(fileName);
    
    var range = [fileName rangeOfString:@"@2.jpg"];
    if (range.location == NSNotFound) {
        continue;
    }
    
    var fullPathFileName = dirPath + fileName;
    NSLog(fullPathFileName);
    
    var doc = acorn.open_(fullPathFileName);
    var size = doc.canvasSize()
    var newWidth = size.width / 2;
    doc.scaleImageToWidth(newWidth);
    
    var endIndex = [fileName length] - 6;
    // How do I stringify this number so I can pass it to NSLog?
    // NSLog(endIndex);
    
    var modFileName = [fileName substringToIndex:endIndex];
    NSLog(modFileName);
    var modFullPathFileName = dirPath + modFileName + ".jpg";
    NSLog(modFullPathFileName);
    
    doc.dataRepresentationOfType("public.png").writeToFile(modFullPathFileName);
    doc.close();
    fileName = [dirEnum nextObject];
}

Some problems I encountered:
  • I could only pass 1 parameter to NSLog. The string format specifiers (%s and %@) just got lost.
  • I could not do while ((fileName = [dirEnum nextObject])). It just couldn't understand that.
  • The class method [NSFileManaged defaultManager] did not work, so I had to init my own. I'm not sure if that is a JSTalk problem or because I've never written an OS X app before and that is normal.
Ug! A buddy just showed me the JavaScript for Automation video from WWCD 2014. I'm so far behind the tech curve, as usual.

2015-07-12

Perl one-liner: files in this directory also in that directory?

It's been too long since I've used Perl. But anyway...

Problem: I copied files from one folder to another folder manually. Are any files missing?

In the below example "." is the single source folder and "../vegetables.xcassets" is the parent folder of various destination folders.

perl -e 'opendir(D,".");@f=grep{/jpg$/}readdir(D);for $i (@f){@g = glob qq("../vegetables.xcassets/*/$i"); $m="Not $i"; if (-f $g[0]) {$m="OK"}; print "$m $g[0]\n";}'

Sample output:

OK ../vegetables.xcassets/oregano_large.imageset/oregano_large.jpg
Not oregano_large@2x.jpg 
OK ../vegetables.xcassets/oregano_small.imageset/oregano_small.jpg
OK ../vegetables.xcassets/oregano_small.imageset/oregano_small@2x.jpg

Here you can see I forgot to copy oregano_large@2x.jpg.

I used Perl because I forgot how awful shell handles spaces in file names, and I tried to do it that way first. I realize my example output does not contain spaces in the file names, but you don't want to see the listing all the way down to "summer squash".

If you are asking why did I not automate the copy of the files, it is because the copy happened with Xcode, and I needed its internal XML configuration mangling to happen at the same time.

2015-04-04

Viewing exception in lldb

It has been a while since I wrote one of these. Time to do it again.

My app aborted on an assertion.

I had the "All Exceptions" breakpoint enabled.


I got this line in Xcode console.
*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3318.93/UITableView.m:1314
In the Debug navigator, I click on the objc_exception_throw frame.


In the Console of the Debug area, I type in:
expr -o -- $eax
And this tells me exactly what my problem is.


Note: the $eax only works in the Simulator. When debugging on an actual device use $r0.

2015-03-02

Object-oriented State pattern with view controllers in Objective-C and iOS

I have a UIViewController subclass that is controlling a view hierarchy which represents a portion of the UI. That portion of the UI can be in one of three modes: browse, edit, or empty. These modes can change back and forth at run time by user actions.

Right now I have code in every method of the view controller that looks like this:

NSAssert(self.mode == SBModeBrowse || self.mode == SBModeEmpty, @"Should not be called in SBMode %d", self.mode);

And this:

if (self.mode != SBModeEmpty)
{
    [self performScrollCompletion];
}

And so on.

Even worse, I'm probably missing a few asserts and if-thens, and the code just happens to work at the moment.

It seems the object-oriented pattern that solves this situation is the State pattern.

It took me a while to figure out how to do this with UIViewController subclasses because the state behavior will affect UIControls wired up via IBOutlets to the view controller itself. How are the behavior classes supposed to manipulate these objects?

Also, I did not read the State pattern explanation closely enough, so I started off trying to subclass my view controller subclasses instead of merely adding a property to them for a behavior object.

I made a simple sandbox project to teach myself how to add the State pattern to view controllers. Here is my specification.
  • Display a UILabel with a number.
  • Display a UIButton.
  • Display a UIStepper.
  • Start in Browse mode.
  • In Browse mode:
    • Only button allows user taps.
    • Only label and button showing.
    • Button title is "Edit" and tapping it goes to Edit mode.
    • Stepper is invisible and does not allow taps.
  • In Edit Mode:
    • Stepper is visible and allows taps.
    • Stepper adjusts number in label.
    • Button title is "Browse" and tapping it does to Browse mode.
  • When exiting Edit mode, if the number in the label is less than 1, then enter Empty mode.
  • In Empty Mode:
    • Stepper is invisible and no taps allowed.
    • Label background is red.
    • Button tap moves to Edit mode.
Here are the classes and code to accomplish this by using the State pattern and view controllers.

InfoKeys.h


#ifndef SandBox3_InfoKeys_h
#define SandBox3_InfoKeys_h
static NSString *const keyButton = @"button";
static NSString *const keyStepper = @"stepper";
static NSString *const keyLabel = @"label";
#endif

ViewControlller.h


@class Behavior;
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *button;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIStepper *stepper;
@property (strong, nonatomic) Behavior *behavior;
@property (assign, nonatomic) uint16_t labelValue;
- (IBAction)buttonTapped:(id)sender;
- (IBAction)stepperTapped:(id)sender;
@end

ViewController.m


#import "ViewController.h"
#import "Behavior.h"
#import "InfoKeys.h"

@implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.behavior = [[Behavior alloc] initWithInfo:@{keyButton: self.button, keyLabel: self.label, keyStepper: self.stepper}];
}

- (IBAction)buttonTapped:(id)sender
{
    [self.behavior buttonTapped:@{keyButton: sender, keyStepper: self.stepper, keyLabel: self.label}];
}

- (IBAction)stepperTapped:(id)sender
{
    [self.behavior stepperTapped:@{keyStepper: sender, keyLabel: self.label}];
}
@end

Behavior.h


@interface Behavior : NSObject
- (instancetype)initWithInfo:(NSDictionary *)info;
- (void)buttonTapped:(NSDictionary *)info;
- (void)stepperTapped:(NSDictionary *)info;
@end

Behavior.m


#import "Behavior.h"
#import "BehaviorBrowse.h"
#import "BehaviorEdit.h"
#import "BehaviorEmpty.h"
#import "InfoKeys.h"

@implementation Behavior {
    Behavior *_mode;
}

- (instancetype)initWithInfo:(NSDictionary *)info
{
    self = [super init];
    if (self) {
        // Prevent problems if subclasses call this method (for example, as super in overrides).
        if ([self isMemberOfClass:[Behavior class]]) {
            _mode = [[BehaviorBrowse alloc] initWithInfo:info];
        }
    }
    return self;
}

- (void)buttonTapped:(NSDictionary *)info
{
    [_mode buttonTapped:info];
    UIStepper *stepper = info[keyStepper];
    // Coming back from Empty should allow mode to go to Edit so user can increase 0 value.
    if (stepper.value < 1 && ![_mode isKindOfClass:[BehaviorEmpty class]]) {
        _mode = [[BehaviorEmpty alloc] initWithInfo:info];
    }
    else {
        if ([_mode isKindOfClass:[BehaviorEdit class]]) {
            _mode = [[BehaviorBrowse alloc] init];
        }
        else { // Coming from Empty ends up here also.
            _mode = [[BehaviorEdit alloc] init];
        }
    }
}

- (void)stepperTapped:(NSDictionary *)info
{
    [_mode stepperTapped:info];
}
@end

BehaviorBrowse.m


#import "BehaviorBrowse.h"
#import "InfoKeys.h"

@implementation BehaviorBrowse

- (instancetype)initWithInfo:(NSDictionary *)info
{
    self = [super init];
    if (self) {
        UIButton *button = info[keyButton];
        UILabel *label = info[keyLabel];
        UIStepper *stepper = info[keyStepper];
        label.text = [NSString stringWithFormat:@"%.0f", stepper.value];
        stepper.alpha = 0.0;
        stepper.userInteractionEnabled = NO;
        // Button title shows user way to go to opposite mode.
        [button setTitle:@"Edit" forState:UIControlStateNormal];
    }
    return self;
}

- (void)buttonTapped:(NSDictionary *)info
{
    UIButton *button = (UIButton *)info[keyButton];
    // Button titles inform user of way back to the mode they are about to leave.
    [button setTitle:@"Browse" forState:UIControlStateNormal];
    UIStepper *stepper = (UIStepper *)info[keyStepper];
    [UIView animateWithDuration:0.3
                     animations:^(void){stepper.alpha = 1.0;}
                     completion:^(BOOL finished) {stepper.userInteractionEnabled = YES;}];
}

- (void)stepperTapped:(NSDictionary *)info
{
    NSAssert(NO, @"Stepper should not be tapable during browse mode.");
}

@end

BehaviorEdit.m


#import "BehaviorEdit.h"
#import "InfoKeys.h"

@implementation BehaviorEdit

- (void)buttonTapped:(NSDictionary *)info
{
    UIStepper *stepper = info[keyStepper];
    UIButton *button = info[keyButton];
    stepper.userInteractionEnabled = NO;
    // Let user know that button can bring them back to Edit from whatever mode comes next.
    [button setTitle:@"Edit" forState:UIControlStateNormal];
    [UIView animateWithDuration:0.3 animations:^(void){stepper.alpha = 0.0;}];
}

- (void)stepperTapped:(NSDictionary *)info
{
    UILabel *label = info[keyLabel];
    UIStepper *stepper = info[keyStepper];
    label.text = [NSString stringWithFormat:@"%.0f", stepper.value];
}

@end

BehaviorEmpty.m


#import "BehaviorEmpty.h"
#import "InfoKeys.h"

@implementation BehaviorEmpty

- (instancetype)initWithInfo:(NSDictionary *)info
{
    self = [super init];
    if (self) {
        UILabel *label = info[keyLabel];
        label.backgroundColor = [UIColor redColor];
        UIStepper *stepper = info[keyStepper];
        stepper.alpha = 0.0;
        stepper.userInteractionEnabled = NO;
    }
    return self;
}

- (void)buttonTapped:(NSDictionary *)info
{
    UIStepper *stepper = info[keyStepper];
    UIButton *button = info[keyButton];
    [button setTitle:@"Browse" forState:UIControlStateNormal];
    UILabel *label = info[keyLabel];
    label.backgroundColor = [UIColor lightGrayColor];
    [UIView animateWithDuration:0.3
                     animations:^(void){stepper.alpha = 1.0;}
                     completion:^(BOOL finished) {stepper.userInteractionEnabled = YES;}];
}

- (void)stepperTapped:(NSDictionary *)info
{
    NSAssert(NO, @"Stepper should not be tapable during empty mode.");
}


I am always interested in hearing better ways to do this.

2015-02-08

The Schwartzian Transform (from Perl) in Swift.

I realize that the "Schwartzian Transform" is not the name of algorithm itself but rather the name of the compact idiom in Perl for the expression of the algorithm. Since Swift has all of split(), join(), and map(), I will attempt to not only duplicate the algorithm, but the idiom itself.

As I write this, I am not certain I will succeed. I'm kind of excited. It is like a stage magic show.

I'm going off the 2006 article from Randal's web site.

Let's do the steps all broken down.

let data = "Bob 10\nSue 7\nJane 12\nBill 10\nJim 1\nNancy 8\n"
let lines = split(data, {$0 == "\n"})
let annotatedLines: Array = map(lines, {[$0, split($0, {$0 == " "})[1]]})
let sortedLines = sorted(annotatedLines, {$0[1] < $1[1]})
let cleanLines = map(sortedLines, {$0[0]})
let result: String = join("\n", cleanLines)
println(result)

Here is what it looks like with println() statements in a playground.


And here it is condensed properly to match the compact Perl idiom.

let data = "Bob 10\nSue 7\nJane 12\nBill 10\nJim 1\nNancy 8\n"
let result2 = join("\n",
    map(
        sorted(
            map(
                split(data, {$0 == "\n"}),
                {[$0, split($0, {$0 == " "})[1]]}),
            {$0[1] < $1[1]}),
        {$0[0]}))
println(result2)

And in the playground to prove it works.


Just so you know, as Xcode ran this code in the playground, my MacBook Pro (15-inch, Late 2011) CPU fans kicked in. I'm pretty sure Perl would not cause that to happen while processing the same data set.

Now, you may be thinking to yourself, "But it didn't work! Ten is not less than seven!" Yes, that is an obvious machine collating sequence problem because my version is doing string comparisons and not numeric.

This is where I think I've found a Swift defect. I can do this:


let stuff = "xxx 13"
let num:Int! = split(stuff, {$0==" "})[1].toInt()
println("num = \(num)")

But when I try to tack toInt() inside map() for annotatedLines, I get an error.


So the summary is that the Perl code is easier to read, it probably doesn't cause my CPU fans to engage, and its flexible scalar type is more convenient than the old integer vs string separation.

Up Next: the Orcish Maneuver.

Xcode build script: Change value in non-compiled file between Debug and Release.

I have a file that contains lines of text. One of those lines should to have a different value between Debug and Release. The file is not handled by the C preprocessor.

I am accomplishing this with an Xcode build script. If you know of something better, please tell me.

Here is the file and its contents.


I want the string "Production" for thing1 to be replaced with "Debug" during development. In my particular situation, if the script fails, it is better that the release value is used during development instead of the debug value escaping into the app store. Therefore, I use the "Production" string as the default value.

Look at Project | Target | Build Phases | Copy Bundle Sources.


I create a new build phase after this one. Select + button (tooltip: Add New Build Phase tool) | New Run Script Phase.


Put the Run Script after Copy Bundle Resources.


The next step unfortunately involves intimate knowledge of shell syntax. To create your own scripts to do different things, you will also be digging around in the Build Setting Reference doc.

Here is the script that does my task relatively safely.


I doubt anyone wants to cut and paste that, but just in case:

echo "CONFIGURATION = $CONFIGURATION"
if [ "$CONFIGURATION" == "Debug" ]; then
    f1="Statham.notJson"
    echo "CONFIGURATION_BUILD_DIR = $CONFIGURATION_BUILD_DIR"
    echo "CONTENTS_FOLDER_PATH = $CONTENTS_FOLDER_PATH"
    f2="$CONFIGURATION_BUILD_DIR/$CONTENTS_FOLDER_PATH/$f1"
    if [ -f $f2 ]; then
        sed -i "" -e '/thing1:/s/Production/Debug/' "$f2"
    else
        echo "File not found: $f2"
    fi
else
    echo "CONFIGURATION is not Debug. Not updating $f1."
fi

I like the echoes in that script because they help to debug it by looking at the build logs.


Here is my Terminal output to test that my changes worked.

$ pwd
/Users/jeff/Library/Developer/Xcode/DerivedData/SandBox2-aiqtaeeaiietgzagreaqpyganmtt/Build/Products/Debug-iphonesimulator/Pen1.app
$ ls -l
total 72
drwxr-xr-x  6 jeff  staff    204 Feb  8 10:11 Base.lproj
-rw-r--r--  1 jeff  staff    920 Feb  8 10:11 Info.plist
-rwxr-xr-x  1 jeff  staff  21240 Feb  8 10:11 Pen1
-rw-r--r--  1 jeff  staff      8 Feb  8 10:11 PkgInfo
-rw-r--r--  1 jeff  staff     67 Feb  8 10:11 Statham.notJson
$ cat Statham.notJson 
# Whatever file.
    thing0: 76
    thing1: "Debug"
oddItem: tulip

Of course, my build settings were Debug at the time. Here is my scheme to prove it.


Let's make sure the changes do not happen if we are building for Release. I update my scheme and build again. The first thing I notice is a difference in the build logs.


That looks good, but let's check for real, but be sure I'm in the right directory when I look.

$ pwd
/Users/jeff/Library/Developer/Xcode/DerivedData/SandBox2-aiqtaeeaiietgzagreaqpyganmtt/Build/Products
$ ls -l
total 0
drwxr-xr-x  4 jeff  staff  136 Feb  7 16:16 Debug-iphoneos
drwxr-xr-x  7 jeff  staff  238 Feb  8 10:11 Debug-iphonesimulator
drwxr-xr-x  6 jeff  staff  204 Feb  8 10:26 Release-iphonesimulator
$ cat Release-iphonesimulator/Pen1.app/Statham.notJson 
# Whatever file.
    thing0: 76
    thing1: "Production"
oddItem: tulip

It worked!

Now, who can spot the (fairly harmless) defect in my shell script?

2015-02-07

How to embed private Objective-C framework into iOS app on Xcode 6.

I'm creating this post since Apple's documentation on this topic is an out-of-date lie that mentions Xcode 2.4. And Stack Overflow is overrun with point collectors who can only answer minor variations of the same question over and over again.

The simplest form of this recipe is easy once you get past a few snags. I hope this helps someone some day before it also falls out of date.

Warning: this only works for iOS 8 or better. I'm not sure the linker should seg fault because of this though.


I start with a project named Pen1 in a workspace named SandBox2.


Elsewhere, I have already created a Cocoa Touch Framework like this.


The framework is a separate project from the SandBox2 workspace. I did this to simulate the scenario of:

  • You created some code in one project.
  • You have to add the code to another project.
  • You thought to yourself, "I'll turn this small chunk of code into a framework."
  • So then you create a separate project to house the framework with the idea of adding it into other projects and workspaces later.


The framework is named BobLib. It consists of 3 main files: BobLib.h, Newhart.h, and Newhart.m. Here are the contents of those files.



I want to use the method doThatThing from the Newhart class in my Pen1 project.

Next is something you must do, and I've only ever seen it mentioned in a WWDC 2014 video. You must select the Newhart.h file in the Project Navigator. Then in the Utilities Area, select the File Inspector. Inside the Target Membership section, you will have to change the value from "Project" to "Public".


If you don't do this, then after you add BobLib to Pen1, the compile of Pen1 will fail because it can't find Newhart.h.



I build BobLib for both simulator and device. After the build, wait for Xcode to index files, and then BobLib.framework in the Project Navigator under Products group will turn from red text (not found, I suppose) to black text. Control-click BobLib.framework and select Show in Finder from the menu.



I open SandBox2 in Xcode. I drag the simulator build of BobLib.framework in Finder into Pen1 in Xcode.


I guess the options to select here are based on what you are doing with your source code control system. I have not worked out the best thing to do for my own environment yet. For this example, I accepted the default choices.


In the project target General settings, I can see that Xcode automatically added the framework to the Linked Frameworks and Libraries section. Thank you, Xcode.


And it will build successfully, but when I ran it in the simulator, I hit this:


With this error message:

dyld: Library not loaded: @rpath/BobLib.framework/BobLib Referenced from: /Users/jeff/Library/Developer/CoreSimulator/Devices/EF59ACE7-ACD5-40CB-92ED-A4BBBBE619F0/data/Containers/Bundle/Application/7151B3F9-A962-44C0-A5A8-84B4AB619697/Pen1.app/Pen1 Reason: image not found

What Xcode did not do is add BobLib to the Embedded Binaries section of the project target General settings. I am not certain if that makes sense or not since I am so new to embedded frameworks.


Hit the + button, add BobLib.framework, and build and run again.

For some reason, after adding it to Embedded Binaries, Xcode adds it again to Linked Frameworks and Libraries. I delete that extra one.


Here is my code in Pen1 that will test if the app can use BobLib. Since I only copied the framework build for simulator, I can only test this out on Simulator.


After doing the above steps. I know the app has successfully used the framework by checking the console.


One final note. The WWDC 2014 video Building Modern Frameworks is bloody frustrating. The speaker is too enamored of himself, but this would be tolerable if he provided useful information. It is mostly slideshow in which he repeats the stuff we all know from the method naming guidelines. He drones on for 45 minutes before we get to see him play around in Xcode for 10 minutes, and then he casually races past crucial details that are not documented anywhere else on Earth but in this damned video.