Monday, June 16, 2014

A first cut at a swift library to display a UIPickerView

Below is my first cut at creating a class that manages the data for a picker view.  The standard examples have your view controller managing the rows and data for the picker.  I think that this is a bad connection of concerns, so I wanted a generic class that will manage the data for me.

The example is a simple polyhedral dice roller, which lets you pick a number of dice, of a certain type, and add a modifier.

Below is a screenshot of the picker.

As you can see I just have a simple picker at the top of the screen.  Right now all it does is print out the results to the console:

selected row [1, d8, +, 0]
selected row [3, d8, +, 0]

selected row [3, d8, +, 2]


The view code is just concerned with establishing the data that we wish to display:

 var delegate:PickerProvider? = nil;
  
    init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
    {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    func getArray(minNum:Int,maxNum:Int) -> Int[]
    {
        var returnValue=Int[]();
        for i in minNum...maxNum
        {
            returnValue.append(i);
        }
        return returnValue;
    }
    
    
    init(coder aDecoder: NSCoder!)
    {
        delegate=nil;
        super.init(coder:aDecoder)
    }
   
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create an array of numbers for dice.  Use the map function to prepend a 'd' in
        // front of them.
        let dieTypes=[4,6,8,10,12,20].map{ (var number) -> String in
            return "d\(number)";
         };
        
       
        // Note that this is actually a (selectedRows:AnyObject[])->() even though it is
        // declared as (selectedRows:AnyObject[]).  If you declare the paraemter of the method
        // to be (value:AnyObject[]) you will get a compile error.
        let returnValue = { (selectedRows: AnyObject[])->() in
            println("selected row \(selectedRows)");
        };
        
        let numDice=getArray(1,maxNum:20);
        let modifiers=getArray(0,maxNum:30);
        let modRolls=["+","-"];
        
        // Pass the callback to the new delegate, as well as the list of arrays.
         delegate=PickerProvider(selectedCall:returnValue
            ,arrays:numDice,dieTypes,modRolls,modifiers);

        // Set the picker view to use the subclass as both a delgate and dataSource.
        pickerView.dataSource=delegate;
        pickerView.delegate=delegate;
    }

    @IBOutlet var pickerView : UIPickerView
  
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

I started from a simple 'single view' template, added a picker view, and set the delegate to be 'pickerView'.

The core of the logic is in the PickerProvider class, this class is designed to be a general supplier of picker information.  Right now it only displays text titles, and will subdivide the picker into equal segments.

class PickerProvider :NSObject, UIPickerViewDataSource,UIPickerViewDelegate
{
    
    var myarrays:Array<Array<AnyObject>>;
    var callback:(value:AnyObject[])->();
   
    
    // The initial method will take a callback for when a selection si made as well
    // as the array of objects to display.
    init(selectedCall:(value:AnyObject[])->(), arrays: Array<AnyObject> ... )
    {
        myarrays=arrays;
        callback=selectedCall
    }
    
    // Standard override return the number of rows for the given component.
    func pickerView(pickerview: UIPickerView!,numberOfRowsInComponent component: Int)
    -> Int
    {
        let array=getArray(component);
        return array.count;
        
    }
    
    // returns the number of 'columns' to display.
    func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int
    {
        return myarrays.count;
    }
    
    // Internal function to retrieve a specific array.
    func getArray( compNum:Int) -> Array<AnyObject>
    {
        return myarrays[compNum];
    }
    
    
    


    // Get the value for a given component.  Just use the standard swift to make it into a string.
    func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String
    {
        let array=getArray(component);

        let value : AnyObject=array[row];
        return "\(value)";
    }
    
    // Right now weight all arrays equally for the size.  For a real approach we would need to be
    
    func pickerView(pickerView: UIPickerView!, widthForComponent component: Int) -> CGFloat
    {
        let numComp:NSNumber=self.numberOfComponentsInPickerView(pickerView);
        let width:Double=pickerView.frame.width;
        let value=width / numComp.doubleValue;
        return value;
    }
    
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
    {
        var returnValue=AnyObject[]();
        for i in 0..myarrays.count
        {
            let selected=pickerView.selectedRowInComponent(i)
            let array=getArray(i);
            let value=array[selected]
            returnValue.append(value);
        }
        self.callback(value:returnValue);

    }
    

}

The core of the logic is in the PickerProvider class, this class is designed to be a general supplier of picker information.  Right now it only displays text titles, and will subdivide the picker into equal segments.

Overall I would say that Swift makes for better written code.  I've done similiar constructions in Objective-C, and this is far cleaner.  The code is very readable, and barring a few quirks of Swift fairly easy to write.

This examples shows several usages of Swift constructs, the Closures are easier to write than blocks and are first class citizens.  The map function is very neat and shows the ability to transform lists.

List creation and manipulation is far less verbose than in Objective-C, as is displaying primitives as a string.

Sunday, June 15, 2014

Holding closures in a member variable

The next problem that was not obvious was that I wanted to have a callback to my main routine from the picker data source.   After some experimentation I declared the following:

    var callback:(value:AnyObject[]);

And I called the initializer with:

init(selectedCall:(value:AnyObject[]), arrays: Array<AnyObject> ... )


However when I declared the following:
 let returnValue = { (selectedRows: AnyObject[]) in
            println("selected row \(selectedRows)");
        };
        
        // Pass the callback to the new delegate, as well as the list of arrays.
        var delegate=PickerProvider(selectedCall:returnValue

            ,arrays:numDice,dieTypes,modRolls,modifiers);

This resulted in the compile time error of:
'(value: @lvalue AnyObject[]) -> $T3' is not identical to '(value: AnyObject[])'
'(AnyObject[]) -> ()' is not convertible to 'AnyObject[]'

What really happened is explained in Apple's swift manual in a note under functions:

Strictly speaking, the sayGoodbye function does still return a value, even though no return value is defined. Functions without a defined return type return a special value of type Void. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ().

The Apple manual has a lot of explanations for how to use closures for existing libraries, but not a lot for how to write your own functions to use closures.  The problem is that my return Value is actually

(selectedRows: AnyObject[])->() 

While the compiler will currently let you declare variables and member functions without the ->(), it will not consider those the same as the real function.

The solution to this one is to declare my code as:

    var callback:(value:AnyObject[])->();
With an initializer of:
    init(selectedCall:(value:AnyObject[])->(), arrays: Array<AnyObject> ... )



Swift is Reference counted, NOT garbage collected

The first error I encountered was two fold, the difference between reference counting and garbage collection.  I was attempting to create a class to manage the data for a multi-level picker, and I dislike the standard practice Apple uses to have the view controller manage the pickers (I think it belongs in the subclass).

In my first attempt I tried the following code: (which would work great in Java)
 // Pass the callback to the new delegate, as well as the list of arrays.
        var delegate=PickerProvider(selectedCall:returnValue
            ,arrays:numDice,dieTypes,modRolls,modifiers);

        // Set the picker view to use the subclass as both a delgate and dataSource.
        pickerView.dataSource=delegate;
        pickerView.delegate=delegate;

When I did this, I would end up with a very obscure error:

014-06-15 21:16:11.737 SimpleDieRoller[11717:13412066] -[CALayerArray numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x10bf05330
2014-06-15 21:16:11.742 SimpleDieRoller[11717:13412066] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayerArray numberOfComponentsInPickerView:]: unrecognized selector sent to instance 0x10bf05330'
*** First throw call stack:
(
 0   CoreFoundation                      0x000000010046ee35 __exceptionPreprocess + 165
 1   libobjc.A.dylib                     0x0000000101f1a9a0 objc_exception_throw + 45
 2   CoreFoundation                      0x00000001004751cd -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
 3   CoreFoundation                      0x00000001003cf89c ___forwarding___ + 988
 4   CoreFoundation                      0x00000001003cf438 _CF_forwarding_prep_0 + 120
 5   UIKit                               0x0000000100cd8398 -[UIPickerView _updateSelectedRows] + 69
 6   UIKit                               0x0000000100cd84ce -[UIPickerView didMoveToWindow] + 78
 7   UIKit                               0x0000000100d57052 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 1496
 8   UIKit                               0x0000000100d56d41 -[UIView(Internal) _didMoveFromWindow:toWindow:] + 711
 9   UIKit                               0x0000000100d4f8e5 __45-[UIView(Hierarchy) _postMovedFromSuperview:]_block_invoke + 128
 10  UIKit                               0x0000000100d4f856 -[UIView(Hierarchy) _postMovedFromSuperview:] + 437
 11  UIKit                               0x0000000100d5968e -[UIView(Internal) _addSubview:positioned:relativeTo:] + 1610
 12  UIKit                               0x0000000100d29c3f -[UIWindow addRootViewControllerViewIfPossible] + 452
 13  UIKit                               0x0000000100d29e22 -[UIWindow _setHidden:forced:] + 276
 14  UIKit                               0x0000000100d369ad -[UIWindow makeKeyAndVisible] + 42
 15  UIKit                               0x0000000100ce4db9 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2753
 16  UIKit                               0x0000000100ce7529 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1222
 17  UIKit                               0x0000000100ce6510 -[UIApplication workspaceDidEndTransaction:] + 19
 18  CoreFoundation                      0x00000001003a5bbc __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
 19  CoreFoundation                      0x000000010039b095 __CFRunLoopDoBlocks + 341
 20  CoreFoundation                      0x000000010039a84c __CFRunLoopRun + 844
 21  CoreFoundation                      0x000000010039a296 CFRunLoopRunSpecific + 470
 22  UIKit                               0x0000000100ce5f26 -[UIApplication _run] + 413
 23  UIKit                               0x0000000100ce9308 UIApplicationMain + 2994
 24  SimpleDieRoller                     0x0000000100006c3d top_level_code + 77
 25  SimpleDieRoller                     0x0000000100006c7a main + 42
 26  libdyld.dylib                       0x0000000102478145 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException


It was not obvious from this what was happening.  What was really happening is that the 'var delegate' local variable was being allocated and given a count of 1.  It was then assigned to
'delegate' and datasource' of the picker.

However those properties are declared:
var dataSource: UIPickerViewDataSource! // default is nil. weak reference
    var delegate: UIPickerViewDelegate! // default is nil. weak reference

The fact that they were weak references, means that when the initializer left scope, the count was decremented, the variable was no longer valid, so the picker called an invalid reference.  

This was an easy fix, I just made a member variable that held my picker source, however the error was so obscure it took a while to find it out.



Introduction to swift

Like most developers I found the introduction of swift to be very interesting.  One of the great barriers to iPhone development was the learning curve for Objective-C.  Swift seems like a very interesting development.  Instead of supporting an existing language they have added a new language that has attempted to diverge from C in many fashions.

Swift has an interesting grab bag of features that it looks like the language designers decided to toss in.


  • Explicit methods for having 'no value' instead of using null.  This means that you can bypass the need that Java has for Double vs double, etc..
  • Enhanced for loops that try to support more expressiveness in terms of what to iterate over
  • Support for more advance switch statements, with no default fall through (a cause of bugs for decades), but which supports 

For a greater introduction to swift the best place is of course Apple's Swift introduction.  It covers the basics of the language, but so far in my brief experiences with Swift there are some gotchas that I have found which were not immediately obvious from the book.

Sunday, March 24, 2013

Displaying an alert view with blocks

The default method for displaying an alert view is somewhat cumbersome if you have a dialog with many possible choices. I had a table cell that had two buttons, one that would add to a number, and one that would subtract. I wanted to then add the ability to directly set the number. As I started adding more choices, I ended up with a cumbersome dialog. The default alert view protocol expects only one callback, so you have to track what dialog you are showing, and have an case statement or if/else block for that. Anytime you see that construct, you know it is time to refactor.

Before

This code starts to get ugly quickly, multiple repeated lines, and the need to put an if/else in my alert callback.  The logic was also hard to follow.

- (IBAction)subtract:(id)sender {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:self.tracker.subtractString message:@"How much:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:self.tracker.subtractString,nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * alertTextField = [alert textFieldAtIndex:0];
    alertTextField.keyboardType = UIKeyboardTypeNumberPad;
    alertTextField.placeholder = [NSString stringWithFormat:@"How much to %@",self.tracker.subtractString];
    self.add=false;
    [alert show];
}
- (IBAction)add:(id)sender {
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:self.tracker.addString message:@"How much:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:self.tracker.addString,nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField * alertTextField = [alert textFieldAtIndex:0];
    alertTextField.keyboardType = UIKeyboardTypeNumberPad;
    alertTextField.placeholder = [NSString stringWithFormat:@"How much to %@",self.tracker.addString];
    @"Enter how much to heal";
    self.add=true;
     [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.cancelButtonIndex!=buttonIndex)
    {
        int num= [[[alertView textFieldAtIndex:0] text] intValue];
        if (self.add)
        {
            self.tracker.currentValue+=num;

        }
        else
        {
            self.tracker.currentValue-=num;
        }
        NSError *error;
        [self.tracker.managedObjectContext save:&error];
        //self.currentLabel.text=[NSString stringWithFormat:@"%d",self.tracker.currentValue];
    }
}

The ability to create a block, an inline method, allows this code to be extracted into a common class, and then made FAR simpler for the receiver.

The first step was creating the alert class that can display an alert view. This class assumes that there is only one prompt active at a time.
@interface AlertButtonHelper : NSObject


@property(nonatomic, copy) void (^action)(NSString *);

- (void)promptForInput:(NSString *)prompt title:(NSString *)title withAcceptButton:(NSString *)acceptButton
          endingAction:(void (^)(NSString *))action keyboardType:(enum UIKeyboardType)keyboardType;

@end

@implementation AlertButtonHelper {


}
// The main command to prompt.
- (void)promptForInput:(NSString *)prompt title:(NSString *)title withAcceptButton:(NSString *)acceptButton endingAction:(void (^)(NSString *))action keyboardType:(enum UIKeyboardType)keyboardType {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:title message:prompt delegate:self cancelButtonTitle:@"Cancel" 
                                           otherButtonTitles:acceptButton,nil];
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        UITextField * alertTextField = [alert textFieldAtIndex:0];
        alertTextField.keyboardType = keyboardType;
        alertTextField.placeholder = [NSString stringWithFormat:prompt];
        
         [alert show];
        self.action=action;
}

// The standard alert callbakc.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    NSString *value = [alertView textFieldAtIndex:0].text;
    if (self.action!=nil)
    {
        self.action(value);
    }
    
}
@end

I ended up with a bunch of blocks that looked like this. Where the only difference was the one line where the number was used.
            void (^actionToTake)(NSString *) = ^(NSString *string) {
                int num= [string intValue];
                self.tracker.currentValue=num;
                NSError *error;
                [self.tracker.managedObjectContext save:&error];

            };
    
I'm using AppCode, which has a nifty extract as block feature.  I used it to transform it into
- (void (^)(NSString *))getModifyFunction:(void (^)(int))modifyValue {
    void (^actionToTake)(NSString *) = ^(NSString *string) {
            int num= [string intValue];
        modifyValue(num);
        NSError *error;
            [self.tracker.managedObjectContext save:&error];

        };
    return actionToTake;
}


 void (^actionToTake)(NSString *)= [self getModifyFunction:^(int num) {
        self.tracker.maxValue = num;
    }];

The final client code is:

- (IBAction)subtract:(id)sender {

    NSString *str=[NSString stringWithFormat:@"How much to %@",self.tracker.subtractString]  ;

    void (^actionToTake)(NSString *)= [self getModifyFunction:^(int num) {
        self.tracker.currentValue -= num;
    }];
        [self.helper promptForInput:str title:self.tracker.subtractString withAcceptButton:self.tracker.subtractString
                       endingAction:actionToTake keyboardType:UIKeyboardTypeNumberPad];

}


- (IBAction)maxSelected:(id)sender {
    NSString *str=[NSString stringWithFormat:@"Enter max Value"]  ;

    void (^actionToTake)(NSString *)= [self getModifyFunction:^(int num) {
        self.tracker.maxValue = num;
    }];
    [self.helper promptForInput:str title:@"Max Value" withAcceptButton:@"Set Max"
                       endingAction:actionToTake keyboardType:UIKeyboardTypeNumberPad];


}

- (void (^)(NSString *))getModifyFunction:(void (^)(int))modifyValue {
    void (^actionToTake)(NSString *) = ^(NSString *string) {
            int num= [string intValue];
        modifyValue(num);
        NSError *error;
            [self.tracker.managedObjectContext save:&error];

        };
    return actionToTake;
}

- (IBAction)add:(id)sender {
    NSString *str=[NSString stringWithFormat:@"How much to %@",self.tracker.addString]  ;

    void (^actionToTake)(NSString *)= [self getModifyFunction:^(int num) {
        self.tracker.maxValue += num;
    }];

    [self.helper promptForInput:str title:self.tracker.addString withAcceptButton:self.tracker.addString
                   endingAction:actionToTake keyboardType:UIKeyboardTypeNumberPad];
}

- (IBAction)currentSelected:(id)sender {
    NSString *str=[NSString stringWithFormat:@"Enter current Value"]  ;

    void (^actionToTake)(NSString *)= [self getModifyFunction:^(int num) {
        self.tracker.currentValue = num;
    }];
            [self.helper promptForInput:str title:@"Set Value" withAcceptButton:@"Set Value"
                           endingAction:actionToTake keyboardType:UIKeyboardTypeNumberPad];
}


I initialize helper in the init method.

 if (self.helper==nil)
    {
        self.helper=[[AlertButtonHelper  alloc] init];
    }
The result has strange syntax, but eliminates a lot of redundant code. The use of blocks is a great way to isolate the 'different' items. The next stage would be to extract a protocol for the alert interface, so that the method of displaying alerts could change if desired.

Tuesday, October 4, 2011

App Code Beta

One of the difficulties that I've had with XCode is that the SDE is not as slick as I'm used to. When combined with some of the peculiarities of the language, it is more painful to code in this than in Eclipse for Java or Visual Studio for C# (especially with the Resharper plugin). I've found that JetBrains, the creators of IntellJ and Resharper have created a SDE called AppCode for Objective C. I've tried it and it is far easier to use for most things than XCode (either 3 or 4). Right now the Beta is free, and you can sign up for a 50% discount on the final product.

I highly recommend it.  The smart code completion is far better, it can automatically make properties for you, it has far better refactoring, and navigation.

The only downsides are that it doesn't support interface builder, or modifying a SQL-Lite database.  Also if you want to modify your project settings you still need to boot up XCode.

XCode 4 static libraries in a project.

I'm actually trying to get back into IOS development. I was attempting to get my static library to work properly in XCode 4. Apple does not make it easy to do this. I found a really good blog article that helps with this. Using Open Source Static Libraries in XCode 4. While written for open source libraries, it works great with my personal static library as well.