Optional Value In Swift

Posted by on Mar 22, 2016 in Swift | No Comments

An optional provides a variable that can be assigned to contain a value, or left or assigned as nil. The pattern below creates and optional variable (note the ?), assigns it a value, then checks if that value has been assigned.

//create optional 
var optionalName: String?
//assign value
optionalName = "Billy"
// check for value
if let name = optionalName {
    greeting = "Hello, \(name)"

Recursion in Swift

Posted by on Mar 21, 2016 in Apple, apps, code, programming, Swift | No Comments

Recursion is when a method or function calls itself.

//depending on what number you give to N, the function will call itself that many times, subtracting 1 from the original N each time through to pass as an argument.

func thisFunctionCallsItself(thisManyTimes: Int) {
    //The next few lines are to set up the proper suffix on the printed result string
    var mySuffix = String()
    //let's get the last two digits from thisManyTimes
    let lastTwoDigits = thisManyTimes % 100
    switch lastTwoDigits {
    case 10...20:
        mySuffix = "th"
        //get the last digit 
        let lastDigit = thisManyTimes % 10
        switch lastDigit {
        case 1:
            mySuffix = "st"
        case 2:
            mySuffix = "nd"
        case 3:
            mySuffix = "rd"
            mySuffix = "th"
    //OK that it.
    //below is where the function calls itself
    if thisManyTimes != 0 {
        thisFunctionCallsItself (thisManyTimes - 1)
        print("This is the \(thisManyTimes)\(mySuffix) time that this function has called itself.")

//call the function.


NSUserDefaults tutorial, on icodeBlog

Posted by on Jun 29, 2013 in Apple, apps, code | No Comments

Check out this article if you need information on using NSUserDefaults in Xcode.

iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

If you have any trouble saving and retrieving the defaults, try synchronizing:

    [[NSUserDefaults standardUserDefaults] synchronize];

XCode breakpoint tip

Posted by on Mar 9, 2013 in Apple, apps, code | No Comments

Use breakpoints to replace NSLog statements while debugging your code.

Screen Shot 2013-05-09 at 9.08.49 AM


1. Add a break point.
2. Hold option + command and click the break point to edit it.
3. Tap the add action button.
3. Add an action or expression like below.

LLDB (debugger) action

po myVar


expr (void)NSLog(@"myVar = %d", myVar)

Select “Automatically continue after evaluating” to continue without stopping the code.


1. Easier to manage: e.g. you can view all the breakpoint and more in the breakpoint navigator (second button from the right in the navigator pane).

2. You can edit the actions or expressions, or add breakpoints while the code is running.

Source: 2012 WWDC video: Debugging in XCode. Much more information in this video.

iOS Core data tutorial, save and fetch an array.

Posted by on Dec 20, 2012 in apps, code, programming | No Comments

1. Open up Xcode and create an empty iOS application (file->new->project, choose the Empty Application template under the iOS->Application section). Click next. Name your project CoreDataSaveArray (though this long name will haunt us later). Make sure to select “Use Core Data” and use ARC too.


2. From the project navigator select the CoreDataSaveArray.xcdatamodeld. This is the file that stores entity descriptions (templates for data objects basically), which make up the data model. Clicking the file will bring up the model editor window, pictured below. Click Add Entity on the bottom left to add an entity. Rename the entity Array. In the attributes section, click the + button to add an attribute to the Array entity. Name the attribute arrayData and set it’s type to string. Create another attribute called name, also a string.


3. Since this is project was started from an empty application, it has no xib or view controllers, so add a view controller and an xib. Click on File->New->File. Select Objective C Class from the Cocoa Touch section. Name your class CoreDataSaveArrayViewController and make sure it is a subclass of UIViewController. Select “With xib” and save the class in your project.

4. Now you need to set this view controller to be the root view controller. Your CoreDataSaveArrayAppDelegate.h should be edited to look like this:

#import <UIKit/UIKit.h>

//add this line
#import "CoreDataSaveArrayViewController.h"

//add this line
@class CoreDataSaveArrayViewController;

@interface CoreDataSaveArrayAppDelegate : UIResponder UIApplicationDelegate;

//add this line
@property (strong, nonatomic) CoreDataSaveArrayViewController *viewController;

@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;


5. Add the lines indicated below to the application:didFinishLaunchingWithOptions method in the CoreDataSaveArrayAppDelegate.m.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    //add this line
    _viewController = [[CoreDataSaveArrayViewController alloc]initWithNibName:@"CoreDataSaveArrayViewController" bundle:nil];
    self.window.backgroundColor = [UIColor whiteColor];
    //add this line
    [self.window setRootViewController:_viewController];
    [self.window makeKeyAndVisible];
    return YES;

6. Create a user interface. Select the CoreDataSaveArrayViewController.xib and add three text fields, two buttons, a label for status output, and other labels to indicate usage as are needed to match the image below. I changed the status label’s background color to gray and the text to white. Create outlets in the CoreDataSaveArrayViewController.h for the text fields and label, as indicated in the image. Also add actions for the buttons.


7. Import the CoreDataSaveArrayAppDelegate.h to the CoreDataSaveArrayViewController.h.

#import UIKit/UIKit;

//add this
#import CoreDataSaveArrayAppDelegate;

@interface CoreDataSaveArrayViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *arrayNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *arrayIndexTextField;
@property (weak, nonatomic) IBOutlet UITextField *arrayDataTextField;
@property (weak, nonatomic) IBOutlet UILabel *outputLabel;
- (IBAction)saveData:(id)sender;
- (IBAction)fetchData:(id)sender;

8. Implement the saveData and fetchData methods as below:

Save Data

- (IBAction)saveData:(id)sender {
    //get instance of app delegate
    CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    //create managed object context
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    //create a managed object, which will be an instance of your entity Array
    NSManagedObject *newArray;
    //create the instance
    newArray = [NSEntityDescription insertNewObjectForEntityForName:@"Array" inManagedObjectContext:context];
    /* Create a string. We are actually going to create an comma separated string of array items, and save that to core data, as array is not a supported type in core data. Then we will make an array out of the string. We can make a string out of an array to if we want to save an array, as I have done in the viewDidLoad method.*/
    [newArray setValue:_arrayDataTextField.text forKey:@"arrayData"];
    [newArray setValue:_arrayNameTextField.text forKey:@"name"];
    //clear the text fields
    _arrayNameTextField.text = @"";
    _arrayDataTextField.text = @"";
    //save the data
    NSError *error;
    [context save:&error];
    //output message
    _outputLabel.text = @"Array saved";

Fetch Data

- (IBAction)fetchData:(id)sender {
    //get instance of app delegate
    CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    //create managed object context
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    //get entity description
    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Array" inManagedObjectContext:context];
    //create a fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setEntity:entityDesc];
    //create predicate to filter request. We will be filtering our search by whatever is in the name text field.
    NSPredicate *pred  = [NSPredicate predicateWithFormat:@"(name = %@)", _arrayNameTextField.text];
    [request setPredicate:pred];
    //put the results in a managed object
    NSManagedObject *matches = nil;
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    //test the results of the search request
    if ([objects count] ==0 ) {
        _outputLabel.text = @"No Array by that name found";
    } else {
        matches = objects[0];
        //get the arrayData (string) and add it to a sting object.
        NSString *arrayString = [matches valueForKey:@"arrayData"];
        //make an array from the string.
        NSArray *array = [arrayString componentsSeparatedByString:@","];
        //cast the index as an int
        int theIndex = [_arrayIndexTextField.text intValue];
        //output the results
        if ([_arrayIndexTextField.text isEqualToString:@""]) {
            //if there is no index number in the array index, just print the name of array and the string
            _outputLabel.text = [NSString stringWithFormat:@"%@: %@",[matches valueForKey:@"name"],arrayString];
        } else {
            //else output the indexed item requested from our array
            if (theIndex >= [array count]) {
                _outputLabel.text = [NSString stringWithFormat:@"There is no %d item in %@", theIndex,[matches valueForKey:@"name"]];
            } else {
                _outputLabel.text = [NSString stringWithFormat:@"%@: Item at %@ is %@",[matches valueForKey:@"name"],_arrayIndexTextField.text, array[theIndex]];

9. Finally modify the viewDidLoad method as below to A. make the output label scale the font dynamically to fit all of the output text, and B. to add a sample array called groceries.

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //make the labels font adjust to fit all the data
    _outputLabel.adjustsFontSizeToFitWidth = TRUE;
    //create sample array called groceries
    NSArray *sampleArray = @[@"bread", @"butter", @"milk", @"cheese", @"cereal"];
    NSString * arrayAsString = [[sampleArray valueForKey:@"description"] componentsJoinedByString:@","];
    CoreDataSaveArrayAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    NSManagedObject *newArray;
    newArray = [NSEntityDescription insertNewObjectForEntityForName:@"Array" inManagedObjectContext:context];
    [newArray setValue:arrayAsString forKey:@"arrayData"];
    [newArray setValue:@"groceries" forKey:@"name"];

To test the app: start by entering groceries in the Array Name field. Then press the Fetch Data button. This should print all the “groceries” in the sample array. Try entering groceries in the Name field and 2 in the index field. This should return the third item in the groceries array. To make a new array, enter a new array name in the Array Name field. Add items, separated by commas, into the array data field. Tap save. This should save the data. You can search your new data as you did the groceries.

Here is the source code: CoreDataSaveArray.zip

Information found in iPhone IOS 6 Development Essentials by Neil Smyth was very helpful. It’s online for free, but you can buy a kindle edition or ebook, as I did.

Programmatic UIpopoverController

Posted by on Jun 30, 2012 in Apple, apps, code | One Comment

Here is an Xcode project that creates an iPad UIPopover with programmatically created glossy buttons (with core graphics). Attempts to match the generic Apple popover buttons.

Basic Objective C object

Posted by on Apr 12, 2012 in apps, code | No Comments

#import <Foundation/Foundation.h>

// the interface
@interface Car : NSObject {
    int wheels;
    int doors; 

-(void) setNumWheels: (int) w;
-(void) setNumDoors: (int) d;
-(void) print;


// the implementation
@implementation Car

-(void) seNumWheels: (int) w{
    wheels = w;

-(void) setNumDoors: (int) d{
    doors = d;

-(void) print { 
    NSLog (@"My car has %i wheels and %i doors.", doors, wheels);  


// the program
int main(int argc, const char * argv[])
    @autoreleasepool {
        Car *myCar;
        myCar = [Car alloc];
        myCar = [myCar init];
        [myCar seNumWheels:4 ];
        [myCar setNumDoors:4];
        [myCar print];

Python, word count

Posted by on Oct 14, 2011 in code, python | No Comments

A simple program that will count the words and sentences in a text file. Sightly modified version of the code I found on daniweb.com.

# count lines, sentences, and words of a text file

# set all the counters to zero
lines, blanklines, sentences, words = 0, 0, 0, 0

# write the trs file
fname = "/path/filename.txt"

# read the file back in
textf = open(fname, "r")

# reads one line at a time
for line in textf:
    #print line,   # test
    lines += 1

    if line.startswith('\n'):
        blanklines += 1
        # assume that each sentence ends with . or ! or ?
        # so simply count these characters
        sentences += line.count('.') + line.count('!') + line.count('?')

        # create a list of words
        # use None to split at any whitespace regardless of length
        # so for instance double space counts as one space
        tempwords = line.split(None)
        #print tempwords  # test

        # word total count
        words += len(tempwords)


print '-' * 50
print "Lines      : ", lines
print "Blank lines: ", blanklines
print "Sentences  : ", sentences
print "Words      : ", words

How to subtitle in After Effects

Posted by on May 5, 2011 in After Effects, code, how to | One Comment

To subtitle in After effects, use the script linked below.


	//	Subtitle generator by !Rocky  http://www.ithowto.ro/2008/12/adobe-after-effects-subtitle-script/
        //     http://vimeo.com/rawkeh
	//	modified by Colin Harman ( http://colinharman.com/ ) to work on a Mac
	//     modified by Oliver to work with CS5
	//	Save this code as
	//	"subtitles.jsx"
	//	Create a text file with your subtitles.
	//	Each line of text is one on-screen line.
	//	To have several lines on-screen at the same time,
	//	simply separate them with a pipe ( | ) character.
	//	eg "Character 1 talks|Character 2 interrupts"
	//	Create a new text layer in your comp, adjust its position,
	//	make sure the text's centered, so it looks nice
	//	Add markers (Numpad *) where each subtitle line must be shown/hidden.
	//	With the text layer selected, run the script, and select the subtitles file.
	//	Enjoy!

	function makeSubs() {
		var layer = app.project.activeItem.selectedLayers[0];

		if (layer.property("sourceText") != null) {
			var textFile = File.openDialog("Select a text file to open.", "");
			if (textFile != null) {
				var textLines = new Array();
				textFile.open("r", "TEXT", "????");

				while (!textFile.eof)
					textLines[textLines.length] = textFile.readln();


				var sourceText = layer.property("sourceText");
				var markers = layer.property("marker");

				for (var i = sourceText.numKeys; i >= 1; i--)

				var line = 0;
				var subTime, subText;
				for (var i = 1; i <= markers.numKeys; i++) {
					subTime = markers.keyTime(i);
					sourceText.setValueAtTime(0, " ");

					if ((i % 2) == 0) {
						subText = " ";
					else {
						subText = textLines[line].replace("|", "\x0d\x0a");
					sourceText.setValueAtTime(subTime, new TextDocument(subText));

PHP, handling forms

Posted by on Jan 26, 2011 in code, how to, web | No Comments

HTML form, which calls a seperate php file, called action.php:

<form action="action.php" method="post">
 <p>Your name: <input type="text" name="name" /></p>
 <p>Your age: <input type="text" name="age" /></p>
 <p><input type="submit" /></p>

The contents of action.php:

Hi <?php echo htmlspecialchars($_POST['name']); ?>.
You are <?php echo (int)$_POST['age']; ?> years old.

Your name:

Your age:


From: A simple tutorial

Load More