Skip to main content


Showing posts from September, 2014

Review: Introducing iOS 8 by Steve Derico (Early Release, O'Reilly Media)

Introducing iOS 8: Swift Programming From Idea to App Store
Steve Derico
Publisher: O'Reilly Media
Release Date: September 2014
Pages: 300 (est.)
Routing successIntroducing iOS 8 is the book for absolute beginners. It opens with a six-stage path to success that starts off with studying the App Store and is designed to provide the easiest way you'll ever encounter for learning to natively program iOS.

Having passed through the essentials of downloading Xcode, the book explains integers, floats, strings, methods, classes and so on at length before progressing onto the model-view-controller (MVC) programming structure. Attempting every possible tactic to keep things light and to prevent intimidation of the beginner.

Of course this is a challenge, because as everyone who has ever programmed an app knows things always inevitably become difficult sooner or later. And in some ways it is a delaying of the inevitable. At the same time if beginners can be guided past those first few step…

Review: Swift Development with Cocoa by Jon Manning, Paris Buttfield-Addison and Tim Nugent (Early Release, O'Reilly)

Swift Development with Cocoa: Developing for the Mac and iOS App Stores
Jon Manning, Paris Buttfield-Addison and Tim Nugent
Publisher: O'Reilly Media
Early Release Ebook: September 2014
Pages: 453 (est.)
Is this book for me? If your ambition is to learn Swift and Cocoa in order to program for iOS and OS X, then Swift Development with Cocoa is aimed directly at you.

The book begins with a bit of background history and some testing and distribution information before throwing us into the details of Swift in Chapter Two ('Programming with Swift'). And while I would recommend reading Apple's Swift book as well for advanced Swift concepts (in particular generics and bridging to Objective-C), it's possible to understand the main parts of Swift from simply reading this chapter. I can also imagine this would be a very useful chapter for a teacher to share with students in order to get them up to speed quickly. In fact teachers could skip over the Preface and Chapter One to …

Dabbling in Android: Editing, Saving, Loading and Deleting Text (Part IIa: Classes, Constructors and Methods)

Every Android project is born with a MainActivity file or equivalent and here you will find the lifecycle methods. The initial one being: onCreate(). But I'm going to ask you to ignore this file for the moment as we continue this tutorial series and instead create a brand new class.
Our class First of all we need to create a new class file inside our Android Studio project from last time. The easiest way to do this is to:
right-click on the src->main->java->com.[your_company_name].[your_app_name] folder and select the top option (Java Class)for the purposes of this tutorial call the file "FileManagement" You should now have a file with a class declaration that looks like this:
public class FileManagement { } This class will handle the creation of files along with the writing, loading and deleting of them. (Of course at the moment it does nothing!)
Constructor Since this class will manage files it needs to know where to save them and so it needs a path to the …

Dabbling in Android: Editing, Saving, Loading and Deleting Text (Part I: Layout)

For the purposes of this tutorial, which will be posted in several parts, you'll need to download Android Studio and install at the very least API 19 using the Android SDK manager.
Create a new app project Inside Android Studio:
File->New Project...give it a nameset to a Minimum SDK of API 14 or above (ignore Wear)select Blank Activitypress Finish Buttons, Buttons, Buttons Assuming you didn't change the default names for the main files in your app you should have a layout file called activity_my.xml (src->main->res->layout->activity_my.xml). And by default Android Studio opens this file for you first of all.

If this is the case make sure first of all that the the API version displayed at the top of the layout window is API 19 or below, then click on the "Design" tab (at the bottom of the window) and drag out three buttons from the palette menu onto your layout, placing them at the top of the screen. (Note: First you'll need to drag aside the "…

Android Studio (Beta 0.8.9): Teething problems with Preview and AVD Emulators

Android Studio is better than Eclipse (ADT) for code prompts and reminding you to update the IDE, but there are some things you still need to do once you've downloaded and installed it in your Applications folder (OS X). The first two of which are essential if you're going to use the Android emulator:

(1) install and update the SDK files using Android SDK manager
(2) create new emulator devices using AVD manager (Android Virtual Device Manager)

Otherwise you'll get a kernel error and you won't be able to run any virtual Android devices.

The third problem I encountered was that in the design preview of the layout file the only option available to me was API 20:4.4W even though I'd set Ice Cream Sandwich as my lowest deployment target. Unfortunately, this is the Android Wear API and doesn't support editable text in a text view, and so was throwing an error about rendering the preview when I tried to add an editable text field.

There was a peculiar solution to th…

Dabbling in Android: File Read and Write

Introduction There's lots of information out there on Android about reading and writing files. It includes buffers and streams and no end of object types to get things working. In order to counteract this, what I came up with here is a beginner's way to read and write to files:
File f = new File(this.getFilesDir(), "hello.txt"); f.createNewFile(); if (f.exists()) { System.out.println("Status: File Created"); FileWriter fw = new FileWriter(f); fw.write("hello world"); fw.close(); FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) { System.out.println("File contents: "+s); } fr.close(); f.delete(); if (!f.exists()) { System.out.println("Status: File Deleted"); } } else System.out.println("Status: File Creation Fa…

Polymorphism and Protocols in Swift (Xcode 6.0.1)

The word polymorphism is not to be found anywhere in a search of Apple's two iBooks about the Swift language (and its use with Objective-C). But don't take this to mean that polymorphism is absent from Swift.
Polymorphism Polymorphism is the ability of a class instance to be substituted by a class instance of one of its subclasses. For example here we have two classes, where B is a subclass of A: class A { func c()->String { return "A" } } class B: A { override func c()->String { return "B" } } Creating a variable with an instance of class A the variable is inferred to be of type A, but polymorphism enables us to switch the value of a to an instance of class B() like so:
var a = A() a = B() There are no compiler complaints about this but if we were to attempt to substitute the value of a for a different class that wasn't a subclass of A then the compiler would raise an error. For example:
class A { func c()->S…

Swift: The difference between a closure and an @autoclosure (Xcode 6 GM)

Closures In Swift, a closure is a type of anonymous function that can be stored as a value and passed as an argument. Or as Apple phrases it:
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages. (Apple) When a method or function takes a closure as one of its arguments the closure is passed inside a pair of code braces.
func num(n: () -> Int) -> Int { return n()*2 } var a = 10 var b = 15 num ({() in a*b}) // returns 300 The above example shows a closure written out in full and passed to the num() function, but normally we'd abbreviate one as simple as this to:
num ({a*b}) // returns 300 Autoclosures Put simply, an autoclosure enables you to omit the braces, but you can only use an autoclosure if the function or method isn't passed any arguments.
func num(n: @autoclosure() -> Int) -> Int { return n()*2 } var a = …

Swift: A basic step-by-step use of a Swift class from an Objective-C file (Xcode 6 GM)

Step-by-Step Instructions 1. create an Objective-C project called ObjCTest

2. create a new Swift file (doesn’t matter what you call it)

3. accept the Bridging Header when offered

4. create a simple class in the Swift file like so:
class CanYouSeeMe: NSObject { var a:String init (str:String){ self.a = str } } Remembering to import Foundation at the head of the file.

5. import Swift header into Objective-C ViewController.m file, e.g. #import "ObjCTest-Swift.h" if project name is ObjCTest. (The header name is your project name with "-Swift.h" appended.)

6. add the following code to your viewDidLoad (ViewController.m):
CanYouSeeMe *cysm = [[CanYouSeeMe alloc] initWithStr:@"Hello"]; NSLog(@"%@",cysm.a); 7. add advance declaration to Objective-C header file @class CanYouSeeMe. As explained by Apple, “To avoid cyclical references, don’t import Swift into an Objective-C header file. Instead, you can forward declare a Swift clas…

Swift: Overriding vs Overloading (Xcode 6 GM)

Overriding and overloading There are two terms to become familiar with here: overriding and overloading. Overriding is when you create a subclass with a function identical (or near identical) to one in its superclass. Whereas overloading is when a function of the same name takes a different type of argument. This is illustrated here:
class A { func aB(a:String){ } } class B: A { override func aB(a:String){ // overriding } func aB(a:Int) { // overloading } } var a = B() a.aB(10) a.aB("hello world") Note: often you'll hear the term operator overloading being used and this follows the same principle  but as the name suggests applies directly to operators.
Overloading a method with the same argument type When you call a class method in Swift, you don't use the parameter name of the first argument (unless you've applied the # modifier). Whereas with an init method you always use the first parameter names. This leads to some di…

Swift: The rules of being optional (Xcode 6 GM)

In a regular Swift protocol every method and property that is declared must be used by any class, struct or enum that adopts the protocol. But this isn't the way it has always been. In Objective-C protocols have optional methods and properties alongside the methods and properties that must be implemented. With Swift these optional methods and properties haven't disappeared, but there are some special requirements in order to get them working.
Exposing your protocol to the Objective-C The first step is to prefix your protocol with the @objc attribute. In brief,
The @objc attribute makes your Swift API available in Objective-C and the Objective-C runtime. (Apple) and I'll provide more details on this in a later post. The important thing here is that @objc attribute opens the possibility of using optional methods and properties in protocols, but it also closes the door on using those @objc protocols with structs and enums. This is because, as with Objective-C protocols, an…

Swift: The rules of being required (Xcode 6 GM)

Regular subclassing Before we consider the role of the required modifier, let's begin with a regular class that has an init() method
class MyClass { var str:String init(str:String) { self.str = str } } and consider what happens when we subclass that class and then create an instance of the subclass:
class MyClass { var str:String init(str:String) { self.str = str } } class MySubClass:MyClass { } var MySubClass(str:"Hello Swift") You'll notice that the subclass instance inherits the init() method from the superclass.

An init() in the subclass Now if we add an init() method to the subclass
class MyClass { var str:String init(str:String) { self.str = str } } class MySubClass:MyClass { override init(str:String) { super.init(str:str) } } var MySubClass(str:"Hello Swift") then the init() must not only use the override modifier to make clear this is what we are doing (i.e. ov…

Swift: The rules of being final (Xcode 6 GM)

The final modifier is used to prevent the subclassing of a class. It is also used to prevent the overriding of properties, methods and subscripts within subclasses of a class that isn't itself final. The keyword is exclusively available to classes, because structs and enums can only inherit from protocols. And although protocols can adopt other protocols, they do not have the capacity to override the protocol that they adopt.
The rules of being finalfinal can be used to prefix a class declaration in order to prevent subclassingfinal can be used within a (non-final) class to prefix a method, property or subscriptfinal cannot be used with structs or enumsfinal can prefix type methods and properties, as well as instance methods and properties Code examples The following code fails to compile, because the Father class is final and cannot be subclassed.
final class Father { // code goes here } class Grandfather:Father { // code goes here } Removing the final keyword it wou…

Swift: The rules of being static (Xcode 6 GM)

The same but different  "In Objective-C, you can define type-level methods only for Objective-C classes. In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports." (Apple) As explained in the above quotation, enums and structs support type methods in Swift. But rather than use the class keyword (as classes do), enums and structs use the static keyword to define type methods. This difference means that when it comes to protocols there is a certain mismatch of terms, as can be seen from this code (adapted from the class post):
enum FoodGroups { case Carbohydrates, Proteins, Fats, Fibre, Minerals, Vitamins } protocol Food { class var varieties:[String] {get} class func goesWith(type:FoodGroups) -> Bool } struct Rice:Food { static var varieties:[String] { return ["white","brown"] } static func goesWith(type:FoodGroups) -> Bool { …

Swift: The rules of being class (Xcode 6 Beta 7)

The three roles of the class keyword (updated 12 September 2014) The class keyword has three roles:
to declare a classto declare type methods and properties within a classto restrict a protocol to adoption by classes only Rules of the first role The rules for the first role are short and in fact there's only one place it before the name of your class when defining/declaring a new Type however this one use does also enable the nesting of classes not only one inside the other, but also inside structs and enums. For example:
struct MyStruct { var a = MyClass() class MyClass { var a:Int = 10; } } MyStruct().a.a // returns 10 Rules of the second role The rules for the second role are as follows: the class keyword can precede a function to transform it into a type method (i.e. a method that can be called via the type name without creating a class instance)the class keyword can precede a computed property to transform it into a type (or class) property the class keywo…

Swift: The rules of being weak and unowned in closures and capture lists (Xcode 6 Beta 7)

Following earlier posts on the weakunowned and lazy keywords, I consider here their use with closures.
Why worry about using weak and unowned in closures? The first thing to do is to explain why we need to use weak and unowned in closures. And the best people to do that are the people writing the Swift documentation, so let's start with why we need to worry about this in our code: If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. (Apple) How to solve the problem with capture lists It can feel like a daunting level of responsibility to not create a strong reference cycle inside a closure, but if we take our time to understand the capture list then our anxieties can be alleviated:  A closure expression can explicitly specify the values that it cap…

Swift: The rules of being lazy (Xcode 6 Beta 7)

Following on from two earlier posts on the rules of the weak and unowned keywords, this post on the lazy keyword is the final one before I examine the rules of pairing the unowned, weak and lazy keywords in closures.
Rules of being lazy"You must always declare a lazy property as a variable (with the var keyword), because its initial value might not be retrieved until after instance initialization completes." (Apple)Lazy is only valid for members of a struct or class (i.e. properties)A  computed property cannot be lazyA closure stored as a property can be lazyMethods and variables within methods cannot be lazy According to the above rules, this is valid:
class LazyFileLoad { lazy var instructions = NSString.stringWithContentsOfFile("/tmp/instructions.txt", encoding: NSUTF8StringEncoding, error: nil) // OK } While this is not:
class LazyFileLoad { lazy var instruct:NSString { return NSString.stringWithContentsOfFile("/tmp/instructions.txt&quo…