Category Archives: IOS

Swift – Structs

If you haven’t heard Swift is a new language from Apple. Swift aims to be a modern language that streamlines your work.

Swift is strongly typed. This means that every value in Swift must be assigned a type.

Here I would like to talk about one feature in Swift called Structs. Struct is short for Structure or Construct. A Struct is similar to an Object in JavaScript.

In Swift a Struct is value. You can think of it as a complex value. If you were to think of a typical value, in a variable you might think:

var x = 230

Here you have a single name, x, representing a single value the number (Int) 230. A Struct is the same, with the difference that a Struct is a structure containing more than a single value. You can think of the difference conceptually as the difference between: nail, and house. Nail is a single discrete element, while a house is single structure, it contains many sub elements.


var nail = 1
struct House {
    var nails = 23000
    var boards = 1200
}

You can see the variable nail holds a single value, while the house has two values: nails, and boards, and could contain any number of other values, like doors, switches outlets etc. Think of a Struct as a way to define an element that contains a group of related values. Imagine everything in your house as a struct:

struct House {
    var nails = 1000
    var boards = 200
    var lightSwitches = 4
    var doors = 3
    var sink = 1
    var toilet = 1
}

var myHouse = House()
println(myHouse.boards)

Structs can also contain functions. In many ways a Struct is similar to a class. From our perspective they act in very much the same ways. Internally the software works them. Structs are assigned as values and Objects created from a Class are assigned as reference.

Copy vs Reference

When assigning a value (this would be how Structs are passed around) the computer creates a copy of the Struct. When you assign an Object you are assigning a reference to the original Object. In short:

Structs are always copied when they are assigned.

Class Objects are not copied when they assigned.

For example:


struct House {
    var address = "123 Maple St."
}

var a = House()
var b = a 
b.address = "321 Elm St."

println(a.address) // prints 123 Maple St.
println(b.address) // prints 321 Elm St.

Here you have two separate Houses. The first (a) would have the address 123, the second would have the address 321.

Here’s what would happen with a Class


class House {
    var address = "123 Maple St"
}

var a = House()
var b = a 
b.address = "321 Elm St."

println(a.address) // prints 321 Elm St.
println(b.address) // prints 321 Elm St.

You have two references to the same house, which moved from it’s original address to the 321 address.

Here is what Apple has to say about structs: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html

Swift – Character vs String

In Swift everything has a type. And these types can be fairly detailed. For example, Swift makes a clear distinction between a single Character, and a Collection of Characters.

Character

A Character in Swift can be any Character, this includes Emoji characters, and any other special character from any language set. You aren’t limited to UTF-8 characters.

Like many other programming languages Swift allows an escape sequence to represent special characters like these:

  • \n Line Feed
  • \r Carriage return
  • \t Tab stop
  • \\ Backslash

Characters also have a Name which describes the Character. For example a might be LATIN-SMALL LETTER A, while an Emoji might be FRONT-FACING BABY CHICK.

String

A String is a collection of Characters. The String has methods that allow us to access each Character in the String, and modify those Characters.

The String Class has so many options I couldn’t list them all here. All of the standard features you would expect exist. Though they might some different names. Things like:

  • substringFromIndex
  • substringToIndex
  • stringByReplacingCharactersInRange
  • stringByReplacingOccurrencesOfString

Parse.com

Screen Shot 2015-06-15 at 1.05.48 PMParse.com is a service that wants to provides a backend for your social media apps. It’s my opinion that Parse is the easiest and fastest way for designers to get into creating social media apps and web sites.

How do we do it now?

The standard method to create a social media app or web site is to create a database and access the database using code written in MySQL. You also need code written in PHP to facilitate transactions with MySQL and manage content from the database. Together this is called the backend. All of these processes happen on a remote computer, your web host.

To have something people can look at you use HTML, CSS, and Javascript. This is called the frontend. You use HTML to structure your web pages, CSS to style them, and javascript to add functionality.

Let’s sum that up. To make a web site that has social media features you need (from front to back):

  • HTMLStructures your data in the browser
  • CSS – Styles the content in the browser
  • Javascript – Adds functionality to the browser
  • PHP – Handles backend services and transactions with the database
  • MySQL – Stores and organizes data

Parse.com

Parse.com provides a service that removes the need for backend programming from the equation. With Parse all of the backend code is handled by the front end. Parse calls itself a: BaaS, which stands for Backend as a Service. The Parse service provides a ready made and hosted backend that can be used to build just about any type of social media app or web site.

Parse saves time by not requiring that you write backend code for creating and configure databases and tables. Parse provides ready made systems for managing user accounts and login. Creating a user login with Parse is as simple as creating the login or sign up form in HTML, CSS, and adding a few lines JavaScript.

For the record, I do not works for Parse and receive nothing from them. As an educator I see Parse as being the easiest way for students to make their social ideas into truly functional apps. For anyone else trying to make their social media ideas into real functioning work, Parse removes many of the roadblocks.

Who would benefit from Parse

Anyone wanting to get started making a social media network would benefit. Parse is well suited to small groups or individuals who want to get started making a social media site. If your skills are more frontend oriented, HTML, CSS, JS, then Parse will save you the trouble of learning PHP, MySQL.

Parse is targeted at startups and small teams looking to create new social media platforms quickly and easily. I see it as a perfect fit for students, as the focus of our students is on front end design and programming. Building an app with Parse moves all of the work of creating a social media app into the front end, and concentrates programming tasks into a smaller set of more familiar tools: HTML, CSS, and JS.

How does Parse work?

In short the Parse service works with Javascript. Essentially you create objects you wish to save in Javascript, and the Parse server takes care of the rest. To display data from the server you request objects from the Parse server through Javascript. Obviously there is a more to it than those two sentences, but not much more.

What kind of things can you make with Parse?

Any social media web site or App. Parse provides libraries code for Xcode, and Android. You can make mobile Application with much less effort, and I’ll say it again, without having to create a backend service, and database. Check out this page of customers using Parse:

https://parse.com/customers

Hello Kitty is using Parse!

 

Cocoa – Creating View Controllers from Code

Starting with an Empty Application, you have a program that contains a single class: AppDelegate and no storyboard. How do you build an application from this? Ignoring main.m and other esoteric code, your application begins at application:didFinishLaunchingWithOptions. When this method is called, your application has an empty window ready for you to populate with interesting objects.

Continue reading Cocoa – Creating View Controllers from Code

Objective-C – Delegates and Protocols

The delegate design pattern creates a system wherein one object passes work to another object. The first object stores a reference to another object, it’s delegate, and calls methods in the delegate object.

To make this system work there are two problems to solve. First. the main class needs a reference to the delegate object. The second problem is the need for the delegate object to implement the methods the delegator object will invoke. Without this guarantee your program runs the risk of no working or crashing.

The first problem is easily solved by adding a property to the delegator that holds a reference to it’s delegate object.

The second problem is solved by declaring a protocol. A protocol declares methods and properties that an object will invoke in it’s delegate. Any class that will act as a delegate implements the protocol, and the methods the defined in the protocol.

When the compiler sees a class that implements a protocol, it checks that the methods declared in the protocol are defined in that class. If not you get a warning or an error.

Declare a protocol in the header file above of @interface with:

@protocol ProtcolName <Class>
-(void)aMethod;
@end

Declare a delegate property to hold an object that implements the protocol. The delegate property should be weak to avoid dependancies!

@property (weak, nonatomic) id <ProtcolName> delegate;

Use the id type here since the delegate object could be of any type.

 

Object-C – Singleton

Singleton is a design pattern that guarantees that only a single instance of a class exists at any time. Singleton classes are good for Models and Datasources. The singleton is a great partner with a UITableView as the datasource for the tableview.

In the header file declare a class method that will return the shared instance. The shared instance is the single instance of this class that will exist. This method is also responsible for creating the new instance the first time the method is invoked.

+(id)sharedManager;

Define this method in the implementation file.

+(id)sharedManager {
    static Things *sharedThings = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedThings = [[self alloc] init];
    });
    return sharedThings;
}

In the sharedManager method declare the variable sharedThings as static. A static variable remembers its value across invocations of a function. That is, the value is set the first time the function is called, and that value is “remembered” the next time the function is called. Normally you would expect that the variable would be forgotten on each subsequent invocation.

The dispatch_once guarantees that the block is contains is only executed once. In the example sharedThings should only be created once, the first time sharedManager is invoked.

The last step is to return the sharedThings instance.

Cocoa – UITableView

These are a  few notes on creating the UITableView. Understand at the time of writing this, I’m a total beginner, so take everything here with a grain salt, and an once of skepticism. The purpose of writing this is to settle subject in my own brain.

As part of the MVC pattern UITableView is a View, so a table view knows how to draw itself. A table view typically needs a view Controller to manage it. A table view always needs a data source. The data source supplies, the number of section, rows, and the content for each row. Typically a table view needs a Delegate. The Delegate handles events generated by the table view.

An instance of the UITableViewController class can handle the role of Controller, Data Source, and Delegate. The UITableViewController, as a view controller, manages a view and this view is always a UITableView.

Any class that manages a UITableView must be a UITableViewDelegate. The data source for the UITableView must be a UITableViewDataSource. These are often the same class, I’m guessing  they don’t have to be.

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@end

This is the UITableView Protocol

To display the UITableView these requirements must be met.

UITableViewDataSource

This protocol requires two methods be implemented:

-(NSInteger)tableView:numberOfRowsInSection
-(UITableViewCell *)tableView:cellForRowAtIndexPath

These two methods tell the UITableView how many cells to work with, and give you the opportunity to populate and configure the UITableViewCells.

Giving the table view the number of rows in a section allows it to get data via the index of that row. Without having to contain the actual data. Essentially tableView:numberOfRowsInSection tells the table view how many cells you will need to work with. When comes time to display a cell, the table view calls on tableView:cellForRowAtIndexPath passing the index of the cell, this function returns the cell; and within this function you populate and configure the cell.

-(NSInteger)tableView:numberOfRowsInSection

This method is relatively simple. It returns the number of cells in the table view. If you were using an array you might implement it in this way:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [array count];
}

– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

The cell For Row method is more complex. Here is where table cells are created, populated, and configured. The table creates cells only as needed. It only creates enough actual cells to fill the screen. As cells scroll up the page they are recycled and repopulated with new data, with the tableview keeping track of which index is currently visible. This process makes the system much more memory efficient, since the computer holds only a limited number of cells in memory. Imagine your iTunes library with 500, or 1000, or more songs. The table view is really only working with enough cells to fill the screen, maybe 10. If the computer to generate 1000 or more table cells, it would slow down, and become unresponsive. Using this system, the table view is recycling a limited number cells like an escalator, changing the content as the cell moves off the top of the view and reappears at the bottom of the view.

You might implement this method as:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *simpleTableIndenitfier = @"SimpleTableCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIndenitfier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIndenitfier];
    }
    
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
    return cell;
}

Here the dequeueReusableCellWithIdenifier asks for an available cell from the table, which is stored in cell. If cell is nil, no cell was available, so a new cell is generated. In this case the cell is generated using the UITableViewCell alloc. Then initialized with initWithStyle. Here we tell initWithStyle to use one of the default cell styles UITableViewCellStyleDefault.

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

This method tells the table view how many sections you will using. Be sure to set this to at least 1. The default implementation of this methods is set 0.

Storyboard and outlets

To connect a tableview created in storyboard to it’s view controller’s outlets, Control drag from the tableView to the view controller and choose dataSource. Repeat the process for delegate. You want the Outlets dataSource and delegate to read ViewController.

Apple HIG – Branding

I see many apps that look like web sites. These often feel the need to brand themselves with a logo and company name in the title bar. Or they present the company logo in a splash screen.

An app is not a web site. Apps are small focussed pieces of software. They live on a mobile device, and in that environment they act in a more personal and intimate role. The icon alone should brand the app. Making the conscious decision to launch an app you know what you are looking at.

Here’s a quote from the HIG:

Incorporate a brand’s assets in a refined, unobtrusive way. People use your app to get things done or be entertained; they don’t want to feel as if they’re being forced to watch an advertisement. For the best user experience, you want to quietly remind users of the brand identity through your choice of font, color, and imagery.

Human Interface Design Guidelines

Apple published a book called the Human Interface Design Guidelines. This covers everything about how to design computer interfaces. I had a print copy some years ago. You can now read it online. It covers everything from color to working with text in different languages.

Apple has also written an IOS version. Here is a great quote from it.

Deference. The user interface helps users understand and interact with the content, but never competes with it.
Clarity. Text is legible at every size, icons are precise and lucid, adornments are subtle and appropriate, and a sharpened focus on functionality motivates the design.
Depth. Visual layers and realistic motion impart vitality and heighten users’ delight and understanding.