Thursday, April 21, 2011

Programming with Core Animation on Mac

Learning notes of Core Animation for Mac OS X and the iPhone

1. The Simplest animation (CABasicAnimation)

Without animation: [theView setFrame:newFrame];

With animation: [[theView animator] setFrame:newFrame];

[theView animator] is the Animator Proxy which is simply finding an animation and then invoking it. The default animation is CABasicAnimation.

2. CAKeyframeAnimation

With CAfeyFrameAnimation, you can define a series of key frames. CoreAnimation system will create animation based on these key frames. For example, we want to create an animation of moving an image to point A, and then B. We only need to create the key frames of A and B. CAKeyframeAnimation could be understood as a series of CABasicAnimation.

// Create the path

NSRect frame = [theView frame];

CGMutablePathRef thePath = CGPathCreateMutable();

CGPathMoveToPoint(thePath, NULL, NSMinX(frame), NSMinY(frame)); //the origin

CGPathAddLineToPoint(thePath, NULL, pointA.x, pointA.y); //Point A

CGPathAddLineToPoint(thePath, NULL, pointB.x, pointB.y); //Point B

// Create an animation

CAKeyframeAnimation *originAnimation = [CAKeyframeAnimation animation];

originAnimation.path = thePath;

originAnimation.duration = 2.0f;

originAnimation.calculationMode = kCAAnimationPaced;

// Add this animation

[theView setAnimations:[NSDictionary dictionaryWithObjectsAndKeys: originAnimation, @”frameOrigin”, nil]];

// Activate this animation

[[theView animator] setFrameOrigin:pointB]; //set the point of the last frame

Monday, April 11, 2011

Add an existing framework in Xcode 4

Steps to add an existing framework in Xcode 4:

1. Click the project in the project navigator.

2. In the project editor, click a target.

3. Select 'Build Phases' tab

4. Expand 'Link Binary With Libraries'

5. Click '+' button to add a framework.

6. Go back to the project navigator, you will see the new framework. You can drag it to 'Frameworks' group.

Friday, April 08, 2011

WWDC2010 Session211 Simplifying iPhone App Development with GCD

GCD Overview

1. GCD is part of libSystem.dylib

2. Available to all Apps.

- #include <dispatch/dispatch.h>

3. GCD API has block-based and function-based variants

- Focus today on block-based API

Introduction to GCD recap

1. Blocks

- dispatch_async()

2. Queues

- Lightweight list of blocks

- Enqueue/dequeue is FIFO

3. dispatch_get_main_queue()

- Main thread/main runloop

4. dispatch_queue_create()

- Automatic helper thread

GCD Advantages

1. Efficiency - More CPU cycles available for your code

2. Better metaphors

- Blocks are easy to use

- Queues are inherently producer/consumer

3. Systemwide perspective

- Only the OS can balance unrelated subsystems

Compatibility

1. Existing threading and synchronization primitives are 100% compatible

2. GCD threads are wrapped POSIX threads

- Do not cancel, exit, kill, join, or detach GCD threads

3. GCD reuses threads

Thursday, April 07, 2011

WWDC2010 Session206 Introducing Blocks and Grand Central Dispatch (2)

Grand Central Dispatch

With GCD, you can make your app responsive. Threading is hard. Using GCD makes it simple and fun. You need not do explicit thread management. Cool!

Keeping your app responsive:

1. Do not block the main thread

2. Move work to another thread

3. Update UI back on main threaad

Code without GCD:

- (void)addTweetWithMsg:(NSString*)msg url:(NSURL*)url {

  // Controller UI callback on main thread

  DTweet *tw = [[DTweet alloc] initWithMsg:msg];

  [tweets addTweet:tw display:YES];

  tw.img = [imageCache getImgFromURL:url];//bottle neck

  [tweets updateTweet:tw display:YES];

  [tw release];

}

Code with GCD:

- (void)addTweetWithMsg:(NSString*)msg url:(NSURL*)url {

  // Controller UI callback on main thread

  DTweet *tw = [[DTweet alloc] initWithMsg:msg];

  [tweets addTweet:tw display:YES];

  dispatch_async(image_queue, ^{

    tw.img = [imageCache getImgFromURL:url];

    dispatch_async(main_queue, ^{

      [tweets updateTweet:tw display:YES];

    });

  });

  [tw release];

}

GCD Queues

1. Lightweight list of blocks

2. Enqueue/dequeue is FIFO

3. Enqueue with dispatch_async()

4. Dequeue by automatic thread or main thread

Main Queue

1. Executes blocks one at a time on main thread

2. Cooperates with the UIKit main run loop

3. dispatch_get_main_queue()

Wednesday, April 06, 2011

WWDC2010 Session206 Introducing Blocks and Grand Central Dispatch (1)

Blocks and Grand Central Dispatch are available on iOS4, and have been available on Snow Leopard.

Technology Stack

Technology Stack Block and Grand Central Dispatch  

Blocks

Blacks are available in C++ and Objective-C++.

Basic Blocks

We will use ^ for blocks because this character is unique and could not be used as operator in C++.

Block Literal Syntax

^ [Return type][Arguments] { Body }

Just looks like a function without function name starting with ^. If no return or no arguments, void could be skipped.

Block Syntax

Blocks as Data

We can define Block pointer. It looks like a function pointer: void (*callable)(void);

void (^callable)(void);

This is an ugly block pointer whose argument is also a block pointer.

char *(^worker)(char *a, BOOL(^done)(int));

We can use typedef to simplify it just like what we do for function pointers:

typedef BOOL (^doneBlk_t)(int);

char *(^workB)(char *a, doneBlk_t d);

WWDC2010 Session313 LLVM Technologies in Depth

This session covers: Clang in Xcode 4 (Code completion, Fix-it, Indexing and Edit-all-in-scope), Clients of LLVM(LLDB, Integrated assembler).

Using Clang Inside Xcode 4

Many contents have been covered in Session 312. Just more examples.

Benefits of LLDB Design

Higher fidelity expression parsing and evaluation

Support all language constructs

     Inline function, template instantiation   

     Debugger gets new language features

Less platform specific knowledge in the debugger

Can pull in other compiler features: Fix-it, code completion

Assembler

LLVM Compiler 2.0 have an integrated assembler. We need not generate .s file and parse big text files. It saves much time.

LLVM assembler

Benefits of LLVM Integrated Assembler:

10% f aster builds (for debug builds of many applications)

Better error messages for inline assembly

More useful assembly dumps

WWDC2010 Session313 LLVM Technologies in Depth

Author: Ted Kremenek - Manager, Compiler Frontend Team

Tuesday, April 05, 2011

WWDC2010 Session312 What's New in the LLVM Compiler

LLVM stands for Low Level Virtual Machine which is a compiler infrastructure, written in C++. The LLVM project started in 2000 at the University of Illinois at Urbana-Champaign, under the direction of Vikram Adve and Chris Lattner. In late 2000, Lattner joined the University of Illinois at Urbana-Champaign as a research assistant and M.Sc. student. Lattner was hired by Apple in 2005.

Compiler Landscape

Three compilers

3 compilers

LLVM Compiler in Xcode 3.2.3 does not support C++. You have to use LLVM-GCC for C++ in Xcode 3.2.3. Now LLVM Compiler 2.0 in Xcode 4 supports C++. That is why the default compiler of Xcode 4 is LLVM Compiler. GCC 4.2 is not recommended because Apple will not fix bugs any more.

WebKit, JavaScriptCore, OpenSSL are built with LLVM in iOS 4. Performance improvement: Open SSL 28%, JavaScriptCore 11%.

LLVM Compiler:

1. Fast compile times - Almost 3x faster debug builds

2. Great user features

3. Beautiful error messages

4. compatible with GCC

Clang Frontend is a parser for C family of languages including C, Objective-C, C++.

Clang is part of many great new tools: LLVM Compiler, Xcode Static Analyzer, Xcode 4, LLDB Debugger, OpenCL. Clang is integrated into Xcode 4 for source code indexing, syntax highlighting, code completion, live warnings and Fix-its.

Xcode Static Analyzer
Automatically find bugs by analyzing your code.

WWDC2010 Session315 Using Interface Builder in Xcode 4

Interface Builder is integrated into Xcode 4.

XcodeI4 Interface Builder

All the window or views in a xib file will show in the design canvas not in a separate window any more.

There is a media library in the interface builder. You can preview and add a picture to your UI directly.

Select a control, press Option key, and move your mouse, you will see some useful annotations.

In Identity Inspector, there is a small arrow at the right side of the class. You can click it to browse the definition of this class.

When you select a control, the Quick Help will show some useful info including sample code.

Connection

Ctrl-drag or right-button drag to make connection, insert IBOutlet, IBAction.

Xcode Assistant content: Top-level objects, custom classes, classes with connections.

It is convenient to use Interface Builder in Xcode 4, though there is no more new about Interface Builder.

WWDC2010 Session315 Using Interface Builder in Xcode 4

Author: Kevin Cathey - Interface Builder Engineer

WWDC2010 Session314 Building and Distributing Your App with Xcode 4

This session covers: How to use the Xcode 4 interface to construct and edit projects and targets. How to construct schemes to build, launch, and archive apps, How to build workspaces to relate multiple projects and share schemes with others.

Editing project settings

When you click the project in the project navigator, you will see the project settings in the editor. It is well organized. If you don't know the meaning of an option, you can click 'Quick help for selected item' in the Help menu. If you have enabled Quick Help tab on the right panel, you will see the quick help there. Very convenient. I notice that the default compiler of a new project is set to LLVM Compiler 2.0.

Editing target settings

Editing target settings is similar to editing project settings. Good news is if you have several targets, you can select some of them to see the differences. In Combined view, the different option shows <Multiple values>. In Levels view, you can see the different value for each target. This is an awesome feature I like.

The editor of 'Run Script' build phase of a target setting now support color-highlighting.

Scheme

Covered by Session307.

Workspace

Covered by Session307.

WWDC2010 Session314 Building and Distributing Your App with Xcode 4

Author: Chris Espinosa - Manager, Xcode Core Tools

Monday, April 04, 2011

WWDC2010 Session308 Developing Your App with Xcode 4

This session covers source control, source editor, find an replace and version editor.

Source control

When you create a new project, you have an option to create a local git repository. You can copy a git link from github.com, create a repository in Organizer, and clone it.

Source editor

Assistant editor - the secondary editor to show related file. For example, if you select .h file, the .m file will show in the assistant editor. You can press Option key and click a file to show it in the assistant editor. Option key works for all items. You can right click an item, press Option key and click 'Jump to definition'. Then the definition shows in the secondary editor.

Auto completion

When you want to implement a method declared in .h file, you need not copy that declaration. You just need to type in a couple of letters of that function name, Xcode will show all unimplemented methods automatically. You can use ctrl-space to invoke it manually. However, looks like Xcode 4 indexes a little bit slow, it does not show my method. I closed my xcode, and restarted it. Then my method showed up. Another problem is the shortcut 'Ctrl-space' conflicts with Spotlight of the OS X.

Code Snippet Library

You can create your code snippet by dragging some lines of code into Code Snippet Library.

Example:

static dispatch_once_t once;

dispatch_once(&once, ^{

});

You can give it a name and the shortcut (key word). And you can also add a token. After you used this code snippet, you just press Tab to move the cursor to that token.

Example:

static dispatch_once_t once;

dispatch_once(&once, ^{

<#code#>

});

WWDC2010 Session307 Introducing Xcode 4

Xcode 4 is an all-in-1IDE just like Visual Studio (I have used Visual Studio for more than 10 years. Comparing to Visual Studio, Xcode 3 is not convenient. Fortunately, Xcode 4 changed it). Interface builder is no longer a separate application. You can write code, design UI, debug in Xcode 4. This session covers workspaces, navigation, editing, organizer, version editor, debugging and schemes.

Xcode4

Workspaces

The workspace is similar to Visual Studio's solution. A workspace works as a container(actually it just references files). You can add several projects into a workspace. Visual Studio 2001 supported the solution. Xcode supported the similar thing 10 years later. The difference is Xcode 4 does not force you to create a workspace. You can open a project directly in Xcode4. But you have to create a solution in Visual Studio even if it contains only one project.

Projects can be shared between workspaces. Every workspace has its own index, build folder.

Navigation

The left panel of Xcode 4 contains several navigators.

1. Project navigator - shows all projects and files

2. Symbol navigator - shows class hierarchies, members, functions

3. Search navigator - find and replace

4. Issue navigator - shows warnings and errors

5. Debug navigator

6. Breakpoint navigator - shows breakpoints

7. Log navigator

WWDC2010 Learning Notes and Index

WWDC 2010 provided many useful videos. I only watched a few videos. Obviously, there is much for us to learn. I am going to force myself to learn most of the videos and put the notes on this site. I will extract the important parts and code of the videos and add some comments. The notes will be used for future reference. I will be glad if you are interested.

It is April 2011 now. Why do I learn WWDC 2010 so late? The answer is simple. I did not have time. When WWDC 2010 was held, I just finished my 6-year service to Autodesk. I was busy in developing my apps. I just learned several videos intensively and added iAd and animation to my apps. Now I want to broaden my mind and learn some new techniques.

You can get WWDC session videos here .

Index

WWDC2010 Session211 Simplifying iPhone App Development with GCD

WWDC2010 Session206 Introducing Blocks and Grand Central Dispatch (1)

WWDC2010 Session206 Introducing Blocks and Grand Central Dispatch (2)

WWDC2010 Session307 Introducing Xcode 4

WWDC2010 Session308 Developing Your App with Xcode 4

WWDC2010 Session312 What's New in the LLVM Compiler

WWDC2010 Session313 LLVM Technologies in Depth

WWDC2010 Session314 Building and Distributing Your App with Xcode 4

WWDC2010 Session315 Using Interface Builder in Xcode 4