๐ Lecture 36 โ Task Combinators, Parallel Loops, and Concurrent Collections
๐ Overview: This lecture covers advanced asynchronous programming patterns using task combinators like
WhenAnyandWhenAll, introduces the Task Parallel Library (TPL) for data parallelism, and explains concurrent collections for thread-safe operations. Understanding these concepts is crucial for building efficient, responsive applications that leverage multicore processors.
๐๏ธ Topics Covered
Task combinators (WhenAny and WhenAll) for coordinating multiple asynchronous operations, implementing timeouts with task combinators, error handling with aggregation, parallel loops (Parallel.For, Parallel.ForEach) with loop states and local values, concurrent collections (ConcurrentBag, ConcurrentStack, ConcurrentQueue, ConcurrentDictionary), BlockingCollection for producer-consumer patterns, and building a producer-consumer queue implementation.
๐ Lecture Summary
Task Combinators: WhenAny and WhenAll
Task combinators allow coordination of multiple asynchronous tasks. Task.WhenAny completes when any of the provided tasks completes, returning the first completed task. Task.WhenAll waits for all tasks to complete and aggregates exceptions. The difference from sequential awaiting (await task1; await task2; await task3;) is that WhenAll runs tasks concurrently. If one task faults with WhenAll, you still get an aggregate exception containing all errors.
๐ Definition โ Task.WhenAny: A combinator that returns a task that completes when any of the supplied tasks completes, returning that task.
๐ Usage: Task winner = await Task.WhenAny(someoperation, Task.Delay(5000)); โ Wait for either operation to complete or timeout
๐ Example: Implementing timeout:
Task<string> task = SomeAsyncFunc();
Task winner = await Task.WhenAny(task, Task.Delay(5000));
if (winner != task) throw new TimeoutException();
string result = await task;
๐ Definition โ **Task.WhenAll**: A combinator that waits for all supplied tasks to complete and returns their results as an array.
๐ Usage: `int[] results = await Task.WhenAll(task1, task2);` โ Returns array of results in same order
๐ Example: Downloading multiple files:
```csharp
async Task<int> GetTotalSize(string[] uris)
{
IEnumerable<Task<int>> downloadTasks = uris.Select(async uri =>
(await new WebClient().DownloadDataTaskAsync(uri)).Length);
int[] contentLengths = await Task.WhenAll(downloadTasks);
return contentLengths.Sum();
}
๐ Definition โ AggregateException: When tasks fault in WhenAll, exceptions are wrapped in an AggregateException with an InnerExceptions collection.
๐ Example: Task all = Task.WhenAll(task1, task2); try { await all; } catch { Console.WriteLine(all.Exception.InnerExceptions.Count); } โ Shows count of all exceptions
๐ก Why this matters: Using WhenAll instead of sequential awaits improves performance by running independent operations concurrently.
Task Parallel Library (TPL) and Parallel Loops
TPL exploits multicore processors for real parallel tasks through three steps: partition work into small chunks, process them in parallel, and collate results in a thread-safe manner. Data parallelism is easier than task parallelism and scales well because the same code starts and ends parallelism in one place. The Parallel class provides three static methods: Parallel.Invoke, Parallel.For, and Parallel.ForEach.
๐ Definition โ Parallel.Invoke: Executes multiple actions in parallel, batching them efficiently for processors.
๐ Usage: public static void Invoke(params Action[] actions);
๐ Example:
Parallel.Invoke(
() => new WebClient().DownloadFile("http://www.linqpad.net", "lp.html"),
() => new WebClient().DownloadFile("http://www.jaoo.dk", "jaoo.html"));
๐ Definition โ Parallel.For: Parallel equivalent of a for loop that partitions iterations across processors.
๐ Usage: public static ParallelLoopResult For(int fromInclusive, int toExclusive, Action<int> body);
๐ Example:
Parallel.For(0, 100, i => Foo(i)); // Parallel version of for (int i=0; i<100; i++) Foo(i);
๐ Definition โ Parallel.ForEach: Parallel equivalent of a foreach loop.
๐ Usage: public static ParallelLoopResult ForEach<TSource>(IEnumerable<TSource> source, Action<TSource> body);
๐ Example:
Parallel.ForEach("Hello, world", c => Console.WriteLine(c.ToString() + c));
Loop Counters, Breaking Out, and Per-Thread Counters
The ParallelLoopState class provides Break() and Stop() methods for controlling loop execution, plus per-thread local state for avoiding lock contention. Break() ensures all iterations before the break point execute (sequential equivalent), while Stop() stops as soon as possible. Local values avoid locking by maintaining thread-local accumulators combined at the end.
๐ Definition โ ParallelLoopState: Provides methods to control parallel loop execution.
๐ Properties: Break(), Stop(), IsExceptional, IsStopped, LowestBreakIteration, ShouldExitCurrentIteration
๐ Example of Break:
Parallel.ForEach("Hello, world", (c, loopState) =>
{
if (c == ',') loopState.Break();
else Console.Write(c);
}); // Output: Hlloe (not sequential because parallel)
๐ Definition โ Local values in Parallel.For: An overload that allows thread-local state for accumulation without shared locks.
๐ Usage: Parallel.For<TLocal>(int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally);
๐ Example:
object locker = new object();
double grandTotal = 0;
Parallel.For(1, 10000000,
() => 0.0, // local init
(i, state, localTotal) => localTotal + Math.Sqrt(i), // body
localTotal => { lock (locker) grandTotal += localTotal; } // local finally
);
Concurrent Collections
Concurrent collections (ConcurrentStack<T>, ConcurrentQueue<T>, ConcurrentBag<T>, ConcurrentDictionary<TKey,TValue>) are optimized for concurrent access. They're thread-safe but conventional collections outperform them except in highly concurrent scenarios. Thread-safe collection doesn't guarantee thread-safe code (enumerating while another thread modifies gives mixed results). Stack, Queue, Bag are implemented with linked lists (less memory efficient). The IProducerConsumerCollection<T> interface provides TryAdd and TryTake methods.
๐ Definition โ ConcurrentBag<T>: An unordered collection that maintains a linked list per thread for minimal contention on Add operations.
๐ Definition โ BlockingCollection<T>: A wrapper that waits (blocks) instead of returning false, with optional bounded capacity. Defaults to a queue.
๐ Usage: BlockingCollection<Action> _taskQ = new BlockingCollection<Action>();
๐ Example: Producer-consumer queue implementation:
public class PCQueue : IDisposable
{
BlockingCollection<Action> _taskQ = new BlockingCollection<Action>();
public PCQueue(int workerCount)
{
for (int i = 0; i < workerCount; i++)
Task.Factory.StartNew(Consume);
}
public void Enqueue(Action action) { _taskQ.Add(action); }
void Consume()
{
foreach (Action action in _taskQ.GetConsumingEnumerable())
action();
}
public void Dispose() { _taskQ.CompleteAdding(); }
}
๐ Definition โ GetConsumingEnumerable: Used with BlockingCollection to iterate over items, blocking when empty, and completing when CompleteAdding is called.
โญ Key Takeaways
The most critical concepts from this lecture: Task.WhenAny enables timeout patterns while Task.WhenAll aggregates results and exceptions from concurrent tasks. Parallel.For/ForEach with ParallelLoopState allow fine-grained control including Break/Stop and per-thread local values for efficient parallel accumulation without shared locks. Concurrent collections like ConcurrentBag and BlockingCollection provide thread-safe storage and are essential for producer-consumer patterns, with BlockingCollection's GetConsumingEnumerable simplifying worker thread implementation. For exam, understand the difference between WhenAll vs sequential awaits, Break vs Stop semantics, and how local values in Parallel.For eliminate lock contention.
๐ง Quick Revision Questions
- What is the difference between
Task.WhenAnyandTask.WhenAll? When would you use each? - How does
ParallelLoopState.Break()differ fromParallelLoopState.Stop()in parallel loops? - Explain how per-thread local values in
Parallel.Forimprove performance over locking. - What is a
BlockingCollection<T>and how doesGetConsumingEnumerable()work? - Why might concurrent collections be slower than conventional collections in low-contention scenarios?
๐ Lecture 37 โ Event Driven Programming on the Web and Mobile
๐ Overview: This lecture transitions from multithreading and task parallelism to event-driven programming on the web and mobile platforms. It covers the evolution from static HTML websites to dynamic, interactive web applications powered by JavaScript, the roles of HTML, CSS, and JavaScript as web technologies, and introduces jQuery as a library to simplify JavaScript development and handle browser incompatibilities.
๐๏ธ Topics Covered
This lecture covers client-side programming and event handling on the web, distinguishes static HTML sites from interactive JavaScript-driven sites, discusses the history and standardization of JavaScript, introduces jQuery as a JavaScript library, explains the structural (HTML), presentation (CSS), and behavioral (JS) layers of web development, covers basic HTML structure and CSS syntax, differentiates client-side vs server-side programming, explains how to embed JavaScript in web pages using <script> tags, covers basic JavaScript syntax (variables, arrays, functions, control flow), and introduces jQuery fundamentals including using CDNs, the document ready function, and basic element selection and manipulation.
๐ Lecture Summary
Tasks and Multithreading Recap
The lecture begins by finishing the discussion on tasks and multithreading, which are important for event-driven and visual programming to remain responsive. Key points from the previous lecture include the Task Parallel Library with Parallel.Invoke, Parallel.For, and Parallel.ForEach. Important concepts covered were the loop counter, Break, Stop, and per-thread counter. The discussion also included concurrent collections like ConcurrentStack, ConcurrentQueue, ConcurrentBag, and ConcurrentDictionary, ending with a producer-consumer queue implemented with tasks.
Web and Mobile Event-Driven Programming
The lecture introduces event-driven programming on the web and mobile, covering client-side programming and event-handling, with a note that server-side web programming is covered in other courses.
Static vs Interactive Websites
Initially, websites were static using HTML (Hypertext Markup Language) which only displayed information. Today, websites achieve the interactivity of desktop applications because of JavaScript. JavaScript enables animation, interactivity, and dynamic visual effects. Examples include: immediately displaying error messages for wrong data, updating totals when items are added to a shopping cart, running slideshows instead of static image lists, expanding and collapsing information, and showing popup tooltips. This provides immediate feedback without the delay of server-side processing and without constant page reloading, making the experience feel like desktop programs. An example cited is Google Maps, where JavaScript enables zooming in and out without reloading, unlike older map sites.
JavaScript History
JavaScript was introduced in 1995 by Netscape, making it about as old as the web itself. Initially, it was used for hobby-like features such as flies following the mouse or moving stock ticker messages. Many scripts didn't work across all browsers and often crashed them. JavaScript has nothing to do with Java; it was originally named LiveScript but renamed to associate with the then-popular Java. Initial interoperability problems existed between Netscape and Internet Explorer (IE), with incompatible features being added. Microsoft introduced JScript, their version of JavaScript for IE. These issues are mostly handled today through standardization, though some quirks remain. The official standardization name is ECMAScript. JavaScript was refueled by high-profile sites like Google using it extensively over the last decade. Now, JavaScript is even used for non-web scripting, including Flash ActionScript (which is based on it), widgets, and phone apps.
jQuery
jQuery is a JavaScript library intended to make JavaScript programming easier by solving JavaScript's complexity and browser incompatibilities. Tasks that would take hundreds of lines of code can be done in a single line of code (LOC) using jQuery. Many advanced features are available as jQuery plugins, and jQuery is used on millions of websites.
The Three Web Layers
The lecture introduces the three layers of web development:
- HTML: The structural layer
- CSS: The presentation layer
- JavaScript: The behavioral layer
HTML Structure
HTML uses simple commands called tags. The <!DOCTYPE html> declaration (for HTML5) tells the browser how to render the page and what standards to follow. There are five types of HTML in use: HTML 4.01 Transitional, HTML 4.01 Strict, XHTML 1.0 Transitional, XHTML 1.0 Strict, and HTML5. All current browsers understand them all. HTML uses starting and closing tags like XML. At least three tags are required: the <html> root tag, the <head> tag containing the title and other metadata, and the <body> tag containing all parts to be rendered in the browser window.
<p></p>is a paragraph<strong></strong>is for emphasis (bold)<a href="http://..."></a>is a hyperlink (XML attribute and value) Validating HTML means checking if all tags are appropriately closed etc.
Example HTML Document
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>Hey, I am the title of this web page.</title>
</head>
<body>
Hey, I am some body text on this web page.
</body>
</html>
CSS (Cascading Style Sheets)
Originally there was only HTML. CSS is a formatting language. HTML is only for structure (e.g., <h1>, <h2> are both headings with different importance, <ul> is an unordered list). CSS adds design. A CSS style is a rule telling the web browser how to display an element. For example, a CSS rule can make all <h1> tags 36 pixels tall, in Courier font, and in orange. CSS can do more powerful things like adding borders, changing margins, and controlling exact placement on a web page. JavaScript can add, remove, or change CSS properties based on user input or mouse clicks, and can even animate from one property to another (e.g., yellow to red, or across the screen by changing position).
CSS Syntax: A single CSS style is a rule that tells how to formatโmake "this" look like "that". It consists of a selector and a declaration block.
- Selector: Can be a headline, paragraph of text, photo, etc.
- Declaration block: Can turn text blue, add red border around a paragraph, position the photo at center of page, etc.
- Example:
p { color: red; font-size: 1.5em; } - Each declaration is a property-value pair followed by a semicolon (
;).
JavaScript (JS) Functionality
JavaScript lets a page re-act. It enables smart web forms that let users know when they miss important information, makes elements appear or disappear, or move around a webpage. It can even load new content from a web server without reloading, creating more engaging and effective websites.
Client-side vs Server-side Programming
Client-side programming uses programming languages for the web browser. The alternative is server-side programming languages like PHP, .NET, ASP, ColdFusion, Ruby on Rails, etc. These run on the web server to handle logic such as accessing databases, processing credit cards, and sending emails. Visitors must wait until the server response comes back. Client-side languages can react immediately, making them more responsive.
Other client-side technologies include applets, Silverlight, and Flash. These often require a plugin or start slowly due to downloading. Sometimes it's difficult to tell if an effect is done with Flash or JavaScript (for example, Yahoo Maps was originally Flash and then rewritten). Right-clicking can reveal if the Flash Player is in use.
Ajax brings client-side and server-side together: JavaScript talks to the server, downloads content, and updates the webpage (as seen in Google Maps). JavaScript is a programming language that can also be used on the server side (e.g., Node.js supports JavaScript on the server-side).
Compiled vs Interpreted Languages
JavaScript is a scripted (interpreted) language. The JavaScript interpreter is built into web browsers. The web browser has two main components:
- A layout or rendering engine (for understanding HTML and CSS)
- A JavaScript interpreter
To tell the web browser about JavaScript, we use a <script></script> tag.
JavaScript in HTML (HTML4 vs HTML5)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>My Web Page</title>
<script type="text/javascript">
</script>
</head>
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
</script>
</head>
JavaScript is usually placed in the <head> section, but it's okay to put it anywhere and in multiple tags. The script can also be placed after </body> so the script is loaded after the page is displayed. External script files can also be used, which are easy to share. Separate script tags are used if you want inline code, and the src attribute is used for external files. Multiple external files can be used.
External JavaScript Files
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="navigation.js"></script>
</head>
<!Doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script src="navigation.js"></script>
<script src="slideshow.js"></script>
<script>Alert('hello world!');</script>
</head>
Basic JavaScript Example
<script>
document.write('<p>Hello world!</p>');
</script>
The document.write function writes content directly into the webpage.
jQuery Example with Fade-in
<link href="../_css/site.css" rel="stylesheet">
<script src="../_js/jquery-1.6.3.min.js"></script>
<script>
$(function () {
$('body').hide().fadeIn(3000);
});
</script>
This example hides the body and then fades it in over 3000 milliseconds (3 seconds).
JavaScript Syntax
JavaScript has syntax similar to C++ and C#:
- Variables: Created using
var x. Names begin with a letter,$, or_. - Arrays:
var days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'];alert(days[0]);displays "Mon"var playlist = [];creates an empty arrayvar prefs = [1, 223, 'www.oreilly.com', false];creates a mixed-type arrayprefs.push('test');adds to the endprefs.unshift('test');inserts at the startshift()gets/removes the first element (queue using push/shift)pop()removes the last element (stack)
- Functions:
alert()andprompt()are built-in functions.
JavaScript Function Example
var TAX = .08;
function calculateTotal(quantity, price) {
var total = quantity * price * (1 + TAX);
var formattedTotal = total.toFixed(2);
return formattedTotal;
}
var saleTotal = calculateTotal(2, 16.95);
document.write('Total cost is: $' + saleTotal);
JavaScript Control Flow
JavaScript supports if, while, for, and do...while statements (similar to C#). Function declarations use the function keyword. There are no types for variables or return values.
jQuery Fundamentals
Many JavaScript programs need to:
- Select elements
- Add new content
- Hide and show content
- Modify tag attributes
- Determine the value of form fields
- React to user actions
The details can be complicated, especially with browser interoperability. Libraries offer a set of functions to make these tasks easy. jQuery is only about 30KB when compressed, easy to learn, used on millions of sites, free, and has a large developer community with many plugins.
CDNs (Content Delivery Networks) can be used instead of hosting jQuery yourself. Google's CDN is very popular. Using CDNs means the library is often cached in the user's browser.
jQuery CDN Examples
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.3.min.js"></script>
<script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
A local copy can also be used:
<script src="js/jquery-1.6.3.min.js"></script>
Document Ready Function
The $(document).ready() function waits until the HTML of the webpage loads and then runs the code. This is necessary because the browser processes in order, and to work with elements, they must be downloaded first.
$(document).ready(function () {
// your programming goes here
});
The shortcut for this is:
$(function () {
// your programming goes here
}); // end ready
Dynamically Changing Webpages
Dynamically changing the webpage is the key idea. It enables effects like mouse-over popups, click-based expand/collapse, and showing detail information. For example, a date picker is run by JavaScript but is itself made of HTML and CSS. The JavaScript just makes the presentation interactive. Two steps:
- Select something (an element)
- Do something with it (change a property, add/remove an element, add/remove extra info, add/remove the
classattribute, or a combination of these)
โญ Key Takeaways
- JavaScript enables interactive, desktop-like experiences on the web by providing immediate feedback without server delays or page reloads, evolving from static HTML to dynamic client-side programming.
- The web development stack has three layers: HTML for structure, CSS for presentation, and JavaScript for behavior, with jQuery simplifying JavaScript development by handling browser incompatibilities and reducing code complexity.
- JavaScript is an interpreted language embedded in web browsers using
<script>tags, with syntax similar to C++/C# but with dynamic typing and no variable types, supporting arrays, functions, control flow, and event handling. - jQuery's
$(document).ready()function ensures code runs only after the HTML document is fully loaded, which is essential for working with page elements, and jQuery simplifies element selection and manipulation in two steps: select something, then do something with it. - Using CDNs for jQuery libraries improves performance through caching, and client-side programming (JavaScript) complements server-side programming (PHP, .NET) by handling immediate user interactions while servers handle database access and complex processing.
๐ง Quick Revision Questions
- What are the three layers of web development according to this lecture, and what role does each play?
- What is the purpose of jQuery, and how does it address the problems of writing JavaScript code?
- Explain the difference between client-side and server-side programming as discussed in this lecture.
- What does the
$(document).ready()function do in jQuery, and why is it important? - How do JavaScript arrays work? Give an example of creating an array, adding an element to it, and accessing an element by index.
๐ Lecture 38 โ HTML DOM and jQuery
๐ Overview: This lecture introduces jQuery as a powerful JavaScript library for HTML DOM manipulation. It covers how jQuery simplifies element selection, content modification, attribute manipulation, event handling, and chaining compared to traditional JavaScript DOM methods, making cross-browser web development more efficient.
๐๏ธ Topics Covered
This lecture covers jQuery selectors (basic and advanced including ID, element, class, descendant, child, sibling, and attribute selectors), jQuery filters (:even, :odd, :first, :last, :not, :has, :contains, :hidden, :visible), jQuery functions for adding, modifying, and removing content (html(), text(), append(), prepend(), after(), remove(), replaceWith()), attribute manipulation (addClass(), removeClass(), toggleClass(), css(), attr(), removeAttr()), the each() method for iterating over selections, and jQuery event handling (mouse events, document/window events, form events, keyboard events) including ready(), hover(), toggle(), and click().
๐ Lecture Summary
HTML DOM vs jQuery Selectors
HTML DOM is much like XML DOM. JavaScript provides ways to select elements, but some browsers allow selecting by CSS while others do not (cross-browser issues). Traditional DOM methods include document.getElementById('banner') and document.getElementsByTagName('a'). To select <a> tags with class navbutton, you must select all <a> tags, then iterate and find those with the right class. In jQuery, $(โselectorโ) simplifies this significantly โ for example, $(โ#bannerโ) selects the tag with id banner, and $(โ#bannerโ).html(โ<h1>JavaScript was here</h1>โ) replaces its content. Html is a jQuery helper function.
Basic Selectors
Basic selectors include ID selectors, element selectors, and class selectors.
๐ Example with ID selector:
<p id="message">Special message</p>
var messagepara = document.getElementById(โmessageโ);
var messagepara = $(โ#messageโ);
๐ Example with element selector:
var linkslist = document.getElementsByTagName(โaโ);
var linkslist = $(โaโ);
๐ Example with class selector:
$(โ.submenuโ)
$(โ.submenuโ).hide();
Advanced Selectors
Advanced selectors include:
- Descendant selectors:
$(โ#navbar aโ)โ selects all<a>elements inside#navbar - Child selectors:
$(โbody > pโ)โ selects<p>elements that are direct children ofbody - Adjacent sibling:
$(โh2 + divโ)โ selects<div>immediately following an<h2> - Attribute selectors:
$(โimg[alt]โ),$(โinput[type=โtextโ]โ),$(โa[href^=โmailto:โ]โ),$(โa[href$=โ.pdfโ]โ),$(โa[href*=โmissingmanuals.comโ]โ), plus form element selectors covered later
๐ Example with attribute selector:
$(โa[href$=โ.pdfโ]โ) selects all anchor tags whose href attribute ends with .pdf.
jQuery Filters
jQuery filters include :even, :odd, :first, :last, :not, :has, :contains, :hidden, :visible.
๐ Examples:
$(โ.striped tr:evenโ) // selects even rows in a striped table
$(โa:not(.navbutton)โ) // selects anchor tags that do NOT have class navbutton
$(โli:has(a)โ) // selects list items that contain an anchor tag (different from descendant)
$(โa:contains(Click Me!)โ) // selects anchor tags containing the text "Click Me!"
$(โdiv:hiddenโ).show() // shows all hidden divs
jQuery Selection Behavior
jQuery selections do not end up with DOM lists but rather jQuery equivalents. jQuery automatically loops over all matched elements.
๐ Chaining functions:
$(โ#popupโ).width(300).height(300)
$(โ#popupโ).width(300).height(300).text(โHi!โ).fadeIn(100)
Chaining allows multiple jQuery methods to be called sequentially on the same selection.
jQuery Functions to Add/Modify Content
Consider this example HTML:
<div id="container">
<div id="errors">
<h2>Errors:</h2>
</div>
</div>
๐ Examples of content manipulation:
alert($(โ#errorsโ).html()); // gets HTML content of #errors
$(โ#errorsโ).html(โ<p>There are four errors in this form</p>โ); // replaces HTML content
$(โ#errors h2โ).text(โNo errors foundโ); // replaces text content
$(โ#errorsโ).append(โ<p>There are four errors in this form</p>โ); // adds content at end
$(โ#errorsโ).prepend(โ<p>There are four errors in this form</p>โ); // adds content at beginning
$(โ#usernameโ).after(โ<span class="error">User name required</span>โ); // adds after element
$(โ#popupโ).remove(); // removes element entirely
$(โ#product101โ).replaceWith(<p>Added to cart</p>โ); // replaces element with new content
$(โa[href^="http://"]โ).addClass(โexternallinkโ); // adds class to matching elements
๐ก Why this matters: These content manipulation methods provide powerful ways to dynamically update webpage content without reloading the page, forming the foundation of modern interactive web applications.
Attribute Manipulation
Attributes can be manipulated with addClass(), removeClass(), toggleClass(), and css().
๐ Examples:
var bgColor = $(โ#mainโ).css(โbackground-colorโ); // gets CSS property
$(โbodyโ).css(โfont-sizeโ, โ200%โ); // sets single CSS property
$(โp.highlightโ).css(โborderโ, โ1px solid blackโ); // sets single CSS property
var baseFont = $(โbodyโ).css(โfont-sizeโ);
baseFont = parseInt(baseFont, 10);
$(โbodyโ).css(โfont-sizeโ, baseFont * 2); // doubles font size
$(โ#highlighteddivโ).css({โbackground-colorโ:โ#FF0000โ,โborderโ:โ2px solid #FE0037โ}); // sets multiple properties
For changing HTML attributes, css() and addClass() are just shortcuts. The general-purpose methods are attr() and removeAttr():
var imageFile = $(โ#banner imgโ).attr(โsrcโ); // gets attribute value
$(โ#banner imgโ).attr(โsrcโ, โimages/newimage.pngโ); // sets attribute value
$(โbodyโ).removeAttr(โbgcolorโ); // removes attribute
Acting on Each Element with each()
When you want to do something special with each element in a selection, use each() with an anonymous function. Use this for the current element as a DOM object, and $(this) for the current element as a jQuery selection.
๐ Example:
$(โselectorโ).each(function () {
// code goes in here
});
$(โa[href^=http://]โ).each(function () {
var extLink = $(this).attr(โhrefโ);
$(โ#biblistโ).append(โ<li>โ + extLink + โ</li>โ);
});
Events
Events are things that happen to a webpage โ page loading, mouse movement, key presses โ and you respond to them with event handlers.
Types of events:
- Mouse events:
click,dblclick,mousedown,mouseup,mouseover,mouseout,mousemove - Document/window events:
load,resize,scroll,unload - Form events:
submit,reset,change,focus,blur - Keyboard events:
keypress(fires repeatedly),keydown,keyup
Steps for event handling:
- Select elements
- Assign an event
- Pass a function to the event
๐ Example:
$(โ#menuโ).mouseover(function () {
$(โ#submenuโ).show();
}); // end mouseover
ready() vs. load() Event
The ready() event fires when the DOM is fully loaded, while the load() event fires when all content (including images) has finished loading.
๐ Example of document ready:
$(function() {
// do something on document ready
});
jQuery Event Methods
Hover combines mouseover and mouseout. Toggle is similar to hover except it works on and off by clicks. The Event object is passed to all functions handling events.
๐ Comprehensive event example:
<script>
$(document).ready(function () {
$(โhtmlโ).dblclick(function () {
alert(โouchโ);
}); // end double click
$(โaโ).mouseover(function () {
var message = "<p>You moused over a link</p>";
$(โ.mainโ).append(message);
}); // end mouseover
$(โ#buttonโ).click(function () {
$(this).val("Stop that!");
}); // end click
}); // end ready
</script>
๐ Hover example:
$(โ#menuโ).hover(function () {
$(โ#submenuโ).show();
}, function () {
$(โ#submenuโ).hide();
}); // end hover
โญ Key Takeaways
jQuery simplifies DOM manipulation by providing cross-browser compatible selectors that automatically loop over matched elements, eliminating the need for manual iteration over DOM lists. The $() function serves as the core selector using CSS-like syntax for ID, class, element, descendant, child, sibling, and attribute selections, along with powerful filters like :even, :odd, :hidden, and :contains. jQuery enables efficient chaining of methods and provides comprehensive content manipulation methods (html, text, append, prepend, after, remove, replaceWith), attribute manipulation (css, addClass, attr, removeAttr), and event handling (click, mouseover, hover, ready) โ all following a consistent three-step pattern: select elements, assign event, pass function. The each() method with $(this) allows custom iteration over selections, while understanding the difference between ready() (DOM loaded) and load() (all content loaded) is essential for proper page initialization.
๐ง Quick Revision Questions
- What is the jQuery equivalent of
document.getElementById('message')anddocument.getElementsByTagName('a')? - How would you select all anchor tags whose href attribute ends with ".pdf" using jQuery?
- What is the difference between
$(โ#errorsโ).html(),$(โ#errorsโ).text(),$(โ#errorsโ).append(), and$(โ#errorsโ).prepend()? - Explain the three-step process for handling events in jQuery, and provide an example using the
hover()method. - What is the purpose of the
each()method in jQuery, and how do you reference the current element as a jQuery object inside it?
๐ Lecture 39 โ Event Properties and jQuery Animations, Forms, and Ajax
๐ Overview: This lecture covers advanced jQuery event handling, including event properties like
String.fromCharCode(evt.which)and methods to stop default browser behavior (evt.preventDefault()andreturn false). It also explains event bubbling and how to stop it, generic event binding, jQuery animations (fade, slide, and custom animate), form handling, and introduces Ajax for asynchronous page updates.
๐๏ธ Topics Covered
The lecture covers event properties and methods (String.fromCharCode, evt.preventDefault, return false, evt.stopPropagation), generic event binding with .bind() and .unbind(), the FAQ toggle example with .next() and .fadeIn(), jQuery animations (fadeIn, fadeOut, slideDown, slideUp, slideToggle, custom animate()), easing, animation chaining with .delay(), a photo gallery example using fadeIn and fadeOut, form handling with .val(), submit() event, focus, blur, change events, and an introduction to Ajax.
๐ Lecture Summary
Event Properties and Methods
The lecture begins with event properties and methods. You can use String.fromCharCode(evt.which) to get the character from a keypress event. To stop normal browser behavior (e.g., following a link, submitting a form), you use evt.preventDefault() or return false. To remove event handlers, use $('.tabbutton').unbind('click'). JavaScript has default event bubbling, where events propagate from the target element up to the document. You can stop this with evt.stopPropagation().
๐ Definition โ evt.preventDefault(): A method that stops the default action of an event (e.g., following a link, submitting a form).
๐ Formula: evt.preventDefault() โ Prevents the browser's default behavior for that event.
๐ Example: To stop a link from navigating: $('a').click(function(evt) { evt.preventDefault(); });
๐ Definition โ evt.stopPropagation(): A method that stops the event from bubbling up to parent elements.
๐ Formula: evt.stopPropagation() โ Prevents the event from triggering handlers on ancestor elements.
๐ Example: To stop a click on a child from triggering the parent's click handler: $('.child').click(function(evt) { evt.stopPropagation(); });
Generic way to bind events: Use .bind() with or without custom data. $('#selector').bind('click', mydata, functionName) passes data to the handler, while $('selector').bind('click', functionName) is equivalent to $('selector').click(functionName).
๐ Formula โ Event positioning: var xpos = evt.pageX; var ypos = evt.pageY; โ Gets the mouse X and Y coordinates relative to the document.
๐ Example:
$(document).click(function (evt) {
var xpos = evt.pageX;
var ypos = evt.pageY;
alert('X:' + xpos + ' Y:' + ypos);
});
๐ Formula โ Binding multiple events: $(document).bind('click keypress', function () { ... }) โ Binds both click and keypress events to the same function.
๐ Example:
$(document).bind('click keypress', function () {
$('#lightbox').hide();
});
You can also bind multiple events with an object syntax:
$('#theelement').bind({
'click': function() { /* do something interesting */ },
'mouseover': function() { /* do something else interesting */ }
});
FAQ Example with Toggle
The FAQ example demonstrates using .toggle() with two functions to create an accordion-like effect. When a heading (h2) is clicked, the next .answer element fades in or out, and a close class is toggled.
๐ Example โ FAQ Toggle:
$(document).ready(function() {
$('.answer').hide();
$('#main h2').toggle(
function() {
$(this).next('.answer').fadeIn();
$(this).addClass('close');
},
function() {
$(this).next('.answer').fadeOut();
$(this).removeClass('close');
}
);
});
jQuery Animations
jQuery provides built-in animation methods. Options include 'slow', 'fast', 'normal', or a number of milliseconds (defaults: slow=600, normal=400, fast=200). Methods include fadeIn(), fadeOut(), fadeToggle(), slideDown(), slideUp(), and slideToggle().
๐ Formula โ Fade animation: $('element').fadeOut('slow'); โ Fades out the element over a slow duration.
๐ Example: $('element').fadeIn(300);
๐ Formula โ Slide animation: $('#login form').slideDown(300); โ Slides down the form element over 300ms.
๐ Example โ Login Slider:
$(document).ready(function () {
$('#open').toggle(
function () {
$('#login form').slideDown(300);
$(this).addClass('close');
},
function () {
$('#login form').fadeOut(600);
$(this).removeClass('close');
}
);
});
Generic Animate: The .animate() method can animate any numeric CSS property. Note that CSS property names with hyphens must be converted to camelCase (e.g., border-left-width becomes borderLeftWidth). You can also use += and -= for relative changes.
๐ Formula โ Custom animate: $('#message').animate({ left: '650px', opacity: 0.5, fontSize: '24px' }, 1500); โ Animates the element over 1500ms, moving it to left 650px, changing opacity to 0.5, and font size to 24px.
๐ Example โ Relative movement:
$('#moveit').click(function () {
$(this).animate({ left: '+=50px' }, 1000);
});
Easing: jQuery supports 'linear' and 'swing' easing. You can also pass a callback function to run when the animation finishes.
๐ Formula โ Easing and callback: $('#element').slideUp(1000, 'linear'); โ Slides up with linear easing.
๐ Example โ Animation with callback:
$('#photo').fadeIn(1000, function () {
$('#caption').fadeIn(1000);
});
๐ Example โ Chaining animations:
$('#photo').width(0).height(0).css('opacity', 0);
$('#caption').hide();
$('#photo').animate(
{ width: '200px', height: '100px', opacity: 1 },
1000,
function() { $('#caption').fadeIn(1000); }
);
Chaining effects: $('#photo').fadeIn(1000).delay(10000).fadeOut(250); โ Fades in, waits 10 seconds, then fades out.
Photo Gallery Example
This example shows how to create a simple photo gallery using event prevention and animation.
๐ Example โ Photo Gallery:
$('#gallery a').click(function(evt) {
evt.preventDefault();
var imgPath = $(this).attr('href');
var oldImage = $('#photo img');
var newImage = $('<img src="' + imgPath + '">');
newImage.hide();
$('#photo').prepend(newImage);
newImage.fadeIn(1000);
oldImage.fadeOut(1000, function(){
$(this).remove();
});
});
$('#gallery a:first').click();
Forms
Form handling with jQuery uses .val() to get or set input values. The submit() event is used to validate forms before submission. Other form events include focus, blur, click, and change (for menus).
๐ Definition โ .val(): Gets or sets the value of form elements (input, select, textarea).
๐ Example โ Calculate total:
<input name="quantity" type="text" id="quantity">
<input name="total" type="text" id="total">
var unitCost = 9.95;
var amount = $('#quantity').val();
var total = amount * unitCost;
total = total.toFixed(2);
$('#total').val(total);
Submit Event: Use .submit() to validate a form before it is sent to the server. Return false to prevent submission.
๐ Example โ Form validation:
$(document).ready(function() {
$('#signup').submit(function() {
if ($('#username').val() == '') {
alert('Please supply a name in the Name field.');
return false;
}
});
});
Focus, Blur, Click, Change: These events are used for interactive form elements. The change event is especially useful for reacting to selections from a drop-down menu.
๐ก Why this matters: Client-side validation with events like submit, focus, and blur improves user experience by providing immediate feedback, reducing server load, and preventing invalid data submission.
Ajax Introduction
The lecture concludes with an introduction to Ajax. Not everything can be done at the client side; pages may need to disappear and reappear. Ajax (Asynchronous JavaScript and XML) lets a webpage ask for information and update itself when the information arrives. The term was coined in 2005 for interactive sites coming from Google (e.g., Google Maps, Gmail).
๐ Definition โ Ajax: Asynchronous JavaScript and XML โ a technique that allows web pages to request and receive data from a server without reloading the page.
๐ Formula: $.ajax({ url: 'server.php', success: function(data) { /* update page */ } }); โ Sends a request and handles the response asynchronously.
๐ Example: Google Maps and Gmail use Ajax to update parts of the page without full page reloads.
โญ Key Takeaways
The most critical concepts from this lecture are: (1) You can stop default browser behavior with evt.preventDefault() and stop event bubbling with evt.stopPropagation(). (2) jQuery animations include fadeIn(), fadeOut(), slideDown(), slideUp(), and a generic animate() for any numeric CSS property โ always convert hyphenated CSS names to camelCase. (3) Animations can be chained with .delay() and accept easing (linear/swing) and callback functions. (4) Form handling uses .val() for values and events like submit, focus, blur, and change for validation and interactivity. (5) Ajax allows asynchronous server communication without page reload, enabling modern interactive web applications like Google Maps and Gmail.
๐ง Quick Revision Questions
- What is the difference between
evt.preventDefault()andevt.stopPropagation()in jQuery? - How would you animate a div's opacity from 0 to 1 while moving it 100px to the right over 2 seconds using jQuery?
- What does
$(this).next('.answer').fadeIn()do in the FAQ example? - How do you get the value of an input field and set the value of another input field using jQuery?
- What does Ajax allow a web page to do that traditional form submission cannot?
๐ Lecture 40 โ Ajax Basics
๐ Overview: This lecture introduces Ajax (Asynchronous JavaScript and XML), a powerful technique for creating responsive web applications that can exchange data with servers without reloading the entire page. It explains how jQuery simplifies Ajax operations, covering the
load(),get(),post()methods, data serialization, error handling, and JSON format.
๐๏ธ Topics Covered
The lecture covers the XMLHttpRequest object and its role in Ajax communication, jQuery's load() method for loading HTML content, $.get() and $.post() methods for sending data to servers, data formatting with query strings and object literals, form serialization, callback functions for processing server responses, error handling, and JSON as a lightweight data exchange format.
๐ Lecture Summary
In Last Lecture...
We discussed event objects and their properties, binding and unbinding events, jQuery animations (easing, chaining), FAQ sections, login sliders, photo galleries, forms and form selectors. Now we move to the real power: Ajax.
What Can Be Done with Ajax
Ajax allows displaying new HTML content without reloading the page, submitting forms and instantly displaying results, and logging in without leaving the page. Examples include star rating widgets and browsing through database information (like scrolling on Facebook or Twitter). Nothing radicalโsame functionality can be achieved with HTML and server-side programming, but Ajax makes pages feel more responsive and desktop-like.
How Ajax Works
JS, server-side programming, and web browser all work together:
- Web browser: Uses the XMLHttpRequest object (also called XHR) that makes Ajax possible by talking to the web server and getting a response
- JS: Sends request, waits for response, processes response, updates web page
- Web server: Receives request and responds as HTML, plain text, XML, or JSON. Application servers handle more complicated tasks
- A web server is needed for Ajax examples
Creating XMLHttpRequest
var newxhr = new XMLHttpRequest();
// Browser incompatibilities exist
// Call open to specify data type and destination
newxhr.open('GET', 'shop.php?Productid=34');
// Can use GET or POST
// Write a callback function that will remove, add, change elements
// Send data
newxhr.send(null); // For GET
newxhr.send('q=javascript'); // For POST
Response handling: Callback invoked when XHR receives status, text response, and possibly XML response:
- status = 200/304: All OK
- status = 404: File not found
- status = 500: Internal server error
- status = 403: Access forbidden
- responseText: Has text of JSON or HTML
- responseXML: Less commonly used
jQuery Simplifies Ajax
The simplest jQuery method is the load() function, which loads HTML into an area of a webpage:
// Load news in a div from a web server
$('#headlines').load('todays_news.html');
// Can only load from same site... Relative URLs possible
// Possible to add only a part of the loaded content
$('#headlines').load('todays_news.html #news');
// Example with click event
$('#newslinks a').click(function() {
var url = $(this).attr('href');
$('#headlines').load(url + ' #newsitem');
return false;
});
GET() and POST() Methods
$.get(url, data, callback);$.post(url, data, callback);
Need server side to do anything else. Server may not return HTML (e.g., database records as XML or JSON). jQuery handles differences of GET and POST. No selector neededโthey stand by themselves.
$.get('ratemovie.php', 'rating=5');
$.post('ratemovie.php', 'rating=5');
Formatting Data
Can send a product number, entire form, or signup data. Format as query string or JS object literal.
Query string format:
URL: http://www.chia-vet.com/products.php?Prodid=18&sessid=1234
GET has a limit (often thousands of characters).
$.get('ratemovie.php', 'rating=5');
$.post('ratemovie.php', 'rating=5');
$.post('ratemovie.php', 'rating=5&user=Bob'); // Query string
// Incorrect (must escape special characters)
'favfood=Mac & Cheese' // Incorrect
// Properly escaped
'favfood=Mac%20%26%20Cheese'
// Using encodeURIComponent
var querystring = 'favFood=' + encodeURIComponent('Mac & Cheese');
$.post('foodchoice.php', querystring);
Object literal format (better way):
{
name1: 'value1',
name2: 'value2'
}
$.post('rankmovie.php', { rating: 5 });
var data = { rating: 5 };
$.post('rankmovie.php', data);
var data = {
rating: 5,
user: 'Bob'
};
$.post('rankmovie.php', data);
// Chaining
var data = $.post('rankmovie.php', {
rating: 5,
user: 'Bob'
});
Form Serialization
Serialize using name/value of form elements:
var formdata = $('#login').serialize();
$.get('login.php', formdata, loginresults);
Processing Data Returned
Callback first argument is data. Servers often use XML or JSON. Second argument is a string about status ("success").
Example: Movie rating:
function processResponse(data, status) {
var newhtml;
newhtml = '<h2>Your vote is counted</h2>';
newhtml += '<p>The average rating for this movie is ';
newhtml += data + '.</p>';
$('#message').html(newhtml);
}
// Using with get
$('#message a').click(function() {
var href = $(this).attr('href');
var querystring = href.slice(href.indexOf('?') + 1);
$.get('rate.php', querystring, processResponse);
return false; // Stop the link
});
Error Handling
$.get(url, data, successFunction).error(errorFunction);
$.get('rate.php', querystring, processResponse).error(errorResponse);
function errorResponse() {
var errormsg = "Your vote could not be processed right now.";
errormsg += "Please try again later.";
$('#message').html(errormsg);
}
JSON (JavaScript Object Notation)
JSON is a method for exchanging data. It's JS, so it's quick and easy for JS. No XML-like parsing needed. JSON is a JS object literal (MUST use quotations if names have spaces etc.).
// Example JSON object
{
firstname: 'Frank',
lastname: 'Smith',
phone: '503-555-1212'
}
// With quotes (needed for names with spaces)
{
'firstname': 'Frank',
'lastname': 'Smith',
'phone': '503-555-1212'
}
Server returns a string formatted like a JSON object literal. jQuery provides the $.getJSON() method. Callback will receive a JSON object.
var bday = {
person: 'Raoul',
date: '10/27/1980'
};
bday.person // 'Raoul'
bday.date // '10/27/1980'
Object literals can be composed of other object literals:
var data = {
contact1: {
firstname: 'Frank',
lastname: 'Smith',
phone: '503-555-1212'
},
contact2: {
firstname: 'Peggy',
lastname: 'Jones',
phone: '415-555-5235'
}
};
data.contact1.firstname // 'Frank'
// Iterating over JSON
$.each(JSON, function(name, value) {
// name and value
});
Like $.get() but data passed to callback:
$.getJSON('contacts.php', 'limit=2', processContacts);
๐ก Why this matters: JSON is the most common data format for modern web APIs. It's lightweight, native to JavaScript, and much easier to work with than XML.
โญ Key Takeaways
Ajax allows web pages to communicate with servers without full page reloads, making applications feel more responsive and desktop-like. The core browser object is XMLHttpRequest (XHR), which jQuery wraps into simple methods like load(), get(), and post(). Data can be sent as query strings or JavaScript object literals, and forms can be serialized using serialize(). Callback functions process server responses, and error handling is done with the .error() method chain. JSON is the preferred data format because it's native JavaScript and requires no parsing, with jQuery's $.getJSON() method providing direct access.
๐ง Quick Revision Questions
- What is the XMLHttpRequest object and what are its three key roles in Ajax communication?
- How does jQuery's
load()method differ from$.get()and$.post()in terms of usage and what they return? - What are the four possible HTTP status codes for XMLHttpRequest responses and what does each mean?
- How do you properly escape special characters in a query string, and why is using an object literal better?
- What is JSON, why is it preferred over XML for JavaScript applications, and how do you send and receive JSON data using jQuery?
๐ Lecture 41 โ Objective-C Messaging and Syntax
๐ Overview: This lecture introduces Objective-C, an extension of C that incorporates Smalltalk-style messaging for object-oriented programming. It covers the core syntax for creating, initializing, and manipulating objects, along with key concepts like subclassing, properties, and dynamic typing, which are fundamental for iOS and macOS development.
๐๏ธ Topics Covered
The lecture begins with the basics of Objective-C messaging syntax, including allocation and initialization of objects. It then demonstrates working with collections like NSMutableArray and NSArray, and explores string manipulation with NSString and logging with NSLog. The discussion moves to subclassing from NSObject, defining instance variables, and implementing getter and setter methods. More advanced topics include instance methods (including overriding description), initializers with multiple parameters, class methods for factory-style object creation, dynamic typing and runtime error handling, and finally, simplified accessor declarations using properties.
๐ Lecture Summary
Objective-C Messaging Basics
Objective-C introduces Smalltalk-style messaging to C, developed in the early 1980s for NeXT computers. It is a simple extension of C. To create an object, you send it an alloc message, followed by an init message. These can be combined with nested message sends.
๐ Definition โ alloc: A class method that allocates memory for a new object instance.
๐ Definition โ init: An instance method that initializes a newly allocated object.
๐ Formula: NSMutableArray *arrayInstance = [[NSMutableArray alloc] init]; โ Allocates and initializes an NSMutableArray object in one step.
Message syntax: [receiver selector arguments]
๐ Example: [arrayInstance addObject:anotherObject]; โ sends the addObject: message to arrayInstance with anotherObject as the argument.
Pairing of labels and arguments is a feature of Objective-C.
๐ Example: In other languages: arrayInstance.replaceObjectsinRangeWithObjectsfromArrayrange(anotherArray, anotherRange);
In Objective-C: [arrayInstance replaceObjectsInRange:aRange withObjectsFromArray:anotherArray range:anotherRange];
Destroy objects using [arrayInstance release]; and set to nil: arrayInstance = nil; to avoid dangling pointers. Sending a message to nil is safe (returns nil). Nil is like null.
Working with Collections: NSMutableArray Example
A complete program demonstrates creating, populating, and iterating over an NSMutableArray.
int main (int argc, const char* argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:@"One"];
[items addObject:@"Two"];
[items addObject:@"Three"];
[items insertObject:@"Zero" atIndex:0];
for(int i = 0; i < [items count]; i++) {
NSLog(@"%@", [items objectAtIndex:i]);
}
[items release];
items = nil;
[pool drain];
return 0;
}
@ is a shortcut for creating NSString objects. NSLog uses format strings for output.
๐ Definition โ NSString: An Objective-C class for working with strings.
๐ Example: NSString *myString = @"Hello, World!"; โ creates an NSString using the @ literal.
int len = [myString length]; โ gets the string length.
len = [@"Hello, World!" length]; โ works directly on a string literal.
myString = [[NSString alloc] initWithString:@"Hello, World!"]; โ alternative creation method.
NSArray and NSMutableArray hold references to objects, not primitives or C structures. Use [NSNull null] to store nil-like values.
๐ Formula: int numberOfObjects = [array count]; โ get the count of objects.
[array insertObject:object atIndex:numberOfObjects]; โ inserts at end. Cannot add beyond end (throws exception).
[array addObject:[NSNull null]]; โ adds a null placeholder.
NSString *object = [array objectAtIndex:0]; โ retrieves an object by index.
๐ก Why this matters: Collections (NSArray, NSDictionary, NSSet) form the backbone of data management in Objective-C applications.
Subclassing and Instance Variables
The root class of the entire Objective-C hierarchy is NSObject. Objective-C keywords start with @. Instance variables are declared within curly braces.
#import <Foundation/Foundation.h>
@interface Possession: NSObject
{
NSString *possessionName;
NSString *serialNumber;
int valueInDollars;
NSDate *dateCreated;
}
@end
๐ Definition โ Interface: Declares a class and its instance variables and methods in a .h file.
๐ Definition โ Instance Variables: Variables that belong to each instance of a class.
Getters and Setters (Accessor Methods)
Methods are declared in the interface and implemented in the implementation file.
@interface Possession: NSObject
{
// instance variables
}
- (void)setPossessionName:(NSString *)str;
- (NSString *)possessionName;
// ... other methods
@end
@implementation Possession
- (NSString *)possessionName {
return possessionName;
}
- (void)setPossessionName:(NSString *)newPossessionName {
possessionName = newPossessionName;
}
@end
๐ Example: Creating and using a Possession object:
Possession *p = [[Possession alloc] init];
[p setPossessionName:@"Red Sofa"];
NSString *str = [p possessionName];
NSLog(@"%@", str); // Prints "Red Sofa"
Instance Methods and Overriding description
Instance methods (indicated by -) can be overridden. The description method returns an NSString representation of the object.
๐ Example: Overriding description:
- (NSString *)description {
NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@ (%@): Worth $%d, recorded on %@",
possessionName, serialNumber, valueInDollars, dateCreated];
return descriptionString;
}
Initializers
Initializers follow the init naming convention. id represents any object type. Every object has an isa pointer to its class, enabling method dispatch (like a vtable).
๐ Definition โ isa pointer: A pointer in every object that points to its class, used for dynamic method lookup.
๐ Example: Multi-parameter initializer:
- (id)initWithPossessionName:(NSString *)name valueInDollars:(int)value serialNumber:(NSString *)snumber {
self = [super init];
if (self) {
[self setPossessionName:name];
[self setSerialNumber:snumber];
[self setValueInDollars:value];
dateCreated = [[NSDate alloc] init];
}
return self;
}
Class Methods
Class methods (indicated by +) are called on the class itself, not instances.
๐ Example: randomPossession class method:
+ (id)randomPossession {
NSArray *randomAdjectiveList = [NSArray arrayWithObjects:@"Fluffy", @"Rusty", @"Shiny", nil];
NSArray *randomNounList = [NSArray arrayWithObjects:@"Bear", @"Spork", @"Mac", nil];
int adjectiveIndex = rand() % [randomAdjectiveList count];
int nounIndex = rand() % [randomNounList count];
NSString *randomName = [NSString stringWithFormat:@"%@ %@",
[randomAdjectiveList objectAtIndex:adjectiveIndex],
[randomNounList objectAtIndex:nounIndex]];
int randomValue = rand() % 100;
NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
'0' + rand() % 10, 'A' + rand() % 26, '0' + rand() % 10, 'A' + rand() % 26, '0' + rand() % 10];
Possession *newPossession = [[self alloc] initWithPossessionName:randomName
valueInDollars:randomValue
serialNumber:randomSerialNumber];
return newPossession;
}
Dynamic Typing and Runtime Errors
Objective-C is dynamically typed. Sending an unrecognized message causes a runtime error.
๐ Example: [items doSomethingWeird]; produces: *** -[NSCFArray doSomethingWeird]: unrecognized selector sent to instance 0x104b40
Objective-C has try-catch for runtime errors, but using loops is often better for programmer errors.
Properties
Properties provide simplified accessor declarations using @property and @synthesize.
๐ Definition โ @property: Declares a property with optional attributes (e.g., nonatomic, copy).
๐ Definition โ @synthesize: Tells the compiler to generate getter and setter methods.
๐ Example:
@interface Possession: NSObject
@property (nonatomic, copy) NSString *possessionName;
@property int valueInDollars;
@end
@implementation Possession
@synthesize possessionName, valueInDollars;
@end
The copy attribute creates a copy of the object being set, while mutableCopy creates a mutable copy.
โญ Key Takeaways
Objective-C extends C with Smalltalk-style messaging where objects are created by sending alloc and init messages, and all method calls use square bracket syntax with labeled arguments. Memory management requires paired release and nil assignments to avoid dangling pointers, while collections like NSMutableArray and NSArray hold object references (use [NSNull null] for nil values). Subclassing from NSObject allows defining instance variables, getters/setters, initializers (with super init pattern), and class methods (marked with +), while the @property and @synthesize keywords provide automatic accessor generation. Dynamic typing means runtime errors occur for unrecognized selectors, but Objective-C handles nil messages safely.
๐ง Quick Revision Questions
- What is the syntax for creating and initializing an NSMutableArray object in Objective-C?
- How do you safely destroy an Objective-C object to avoid a dangling pointer?
- What is the purpose of the
@propertydirective, and what attributes can it take? - How does a class method differ from an instance method in terms of declaration syntax and usage?
- What happens when you send a message to
nilin Objective-C, and why is this behavior useful?
๐ Lecture 42 โ Alloc and dealloc methods. Manual reference counting. Obj knows owner count retaincount. Retain and release methods. Should you release a created object that is returned ?. Want to say donโt release but i donโt want to be the owner. Autorelease. Added to nsautoreleasepool. Nsobject *x = [[[nsobject alloc] init] autorelease];.
๐ Overview: This lecture covers manual memory management in ObjectiveโC, focusing on reference counting, the retain and release methods, and the autorelease mechanism. The lecture then transitions to iOS programming, explaining the ModelโViewโController (MVC) pattern and demonstrating how to build a simple quiz app using Xcode and Interface Builder.
๐๏ธ Topics Covered
The lecture begins with memory management concepts: alloc, dealloc, manual reference counting, retain, release, autorelease, and the NSAutoreleasePool. It then shifts to iOS development, covering Xcode projects, Xib/Nib files, the MVC pattern, Interface Builder outlets and actions (IBOutlet, IBAction), and the complete implementation of a quiz application with questions and answers arrays.
๐ Lecture Summary
Alloc and dealloc methods. Manual reference counting. Obj knows owner count retaincount. Retain and release methods.
Every ObjectiveโC object has a retain count (also called owner count). When an object is created with alloc, init, new, or copy, its retain count is 1, and the caller owns the object. To take ownership of an object you did not create, you call retain, which increments the retain count. When you no longer need the object, you call release or autorelease, which decrements the retain count. When the retain count reaches zero, the object is deallocated (its dealloc method is called). You must never release objects you do not own.
๐ Definition โ Retain Count: The integer value stored in an object that indicates how many owners the object has. Each retain increments it; each release decrements it. When it hits 0, dealloc is called.
๐ Rule: If the method name contains init, new, or copy, you own the returned object. Otherwise, you do not own it and must assume it will be autoreleased.
๐ Example:
Nsobject *x = [[[nsobject alloc] init] autorelease];
Here, alloc gives ownership, but autorelease hands that ownership to the nearest NSAutoreleasePool, which will release the object at the end of the current run loop iteration.
Should you release a created object that is returned? Want to say donโt release but i donโt want to be the owner. Autorelease.
When a method creates an object and returns it to the caller, you face a dilemma: you donโt want to release it immediately (the caller needs it), but you also donโt want to be the permanent owner. The solution is autorelease. By sending autorelease instead of release, you mark the object for release later, usually when the current NSAutoreleasePool is drained. The caller can then use the object without worrying about ownership; if the caller wants to keep it, they call retain.
๐ Definition โ Autorelease: A mechanism that defers the release of an object until the end of the current runโloop cycle. The object is added to the nearest NSAutoreleasePool, which sends it a release when drained.
๐ Example: The description method creates a temporary string, autoreleases it, and returns it:
- (Nsstring *)description {
Nsstring *descriptionstring = [[nsstring alloc] initwithformat:@"\%@ (\%@): Worth \$\%d, Recorded on \%@",
Possessionname, Serialnumber, Valueindollars, Datecreated];
return [descriptionstring autorelease];
}
A more concise version uses a class convenience method that internally autoreleases:
- (Nsstring *)description {
return [nsstring stringwithformat:@"\%@ (\%@): Worth \$\%d, Recorded on \%@",
Possessionname, Serialnumber, Valueindollars, Datecreated];
}
Retain count rules. Init, new, copy in name. Assume you own. Any other means. Assume in autorelease. If you donโt own and want to make sure, call retain. No longer need and own than release or autorelease. When 0 count, dealloc called.
The core memory management rules:
- Ownership rules: If you create an object using
alloc,init,new, orcopy, you own it. For any other method (e.g., class factory methods), you do not own it; it is assumed to be in an autorelease pool. - Taking ownership: If you do not own an object but want to guarantee it stays alive, call
retain. - Releasing ownership: When you own an object and no longer need it, call
releaseorautorelease. - Deallocation: When the retain count drops to zero, the runtime automatically calls
dealloc; you must overridedeallocto release the objectโs own instance variables.
๐ Formula: Own ? โ retain (if you want to keep it) No longer need? โ release or autorelease
๐ Example: A typical setter that uses retain/release:
- (void)setpossessionname:(nsstring *)str {
[str retain];
[possessionname release];
Possessionname = str;
}
And the dealloc method that releases all owned instance variables:
- (void)dealloc {
[possessionname release];
[serialnumber release];
[datecreated release];
[super dealloc];
}
Protocols i.e. Interfaces.
Protocols in ObjectiveโC are similar to interfaces in other languages. A protocol declares a set of methods that a class can choose to implement. It allows unrelated classes to respond to the same messages without inheritance.
Last lecture about ajax. Really learned how similar event driven programming is in JS than wpf. What about mobile. Same paradigm, different language. Same concepts, different incarnation. Ios programming. Learn objective-C. Event driven programming. Well see examples but you may not be able to try them. Need a mac computer and Xcode, the ios simulator. Letโs make a simple app.
The lecture shifts to iOS programming, noting that eventโdriven programming in iOS uses the same paradigm as JavaScript and WPF but with ObjectiveโC. To build iOS apps, you need a Mac with Xcode and the iOS Simulator. The example project is a quiz app that displays a question and reveals the answer.
A quiz showing a question and revealing the answer. Create new project (window based applica.). Name it.
You start by creating a WindowโBased Application in Xcode. The user interface is defined in a Xib file (compiled to a Nib file). An iOS application is a directory containing executables and resources, similar to other platforms.
๐ Definition โ Xib/Nib: An XML file (.xib) that describes the user interface; when compiled, it becomes a .nib (Nextstep Interface Builder) file that is loaded at runtime.
Xib editing. Select window to add controls. Drag buttons. Give them names.
Use Interface Builder to select the Window, drag UI controls (like buttons and labels) onto the window, and set their properties (e.g., names, text).
Mvc pattern. View objects. Visible things. Uiview subclasses. Model objects. Hold data and know nothing about interface. Often use standard containers. Controllers keep things in sync.
The ModelโViewโController (MVC) pattern separates the app into three layers:
- View objects: Visible UI elements (subclasses of
UIView). - Model objects: Hold data and business logic; they know nothing about the interface. Often use standard container classes (e.g.,
NSMutableArray). - Controller objects: Keep the model and view in sync, responding to user interactions and updating the display.
Iboutlet, ibaction.
In Interface Builder, IBOutlet is a keyword used to connect a property in code to a visual element in the Xib. IBAction is a keyword used to mark a method as capable of receiving events from controls (e.g., button taps).
Interface and implementation of the quiz app delegate.
The quiz app uses a delegate object (conforming to <UIApplicationDelegate>) to manage the applicationโs lifecycle and UI logic.
Interface (QuizAppDelegate.h):
@interface QuizAppDelegate : Nsobject <UIApplicationDelegate> {
int currentquestionindex;
// The model objects
Nsmutablearray *questions;
Nsmutablearray *answers;
// The view objects
IBOutlet UILabel *questionfield;
IBOutlet UILabel *answerfield;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
- (IBAction)showquestion:(id)sender;
- (IBAction)showanswer:(id)sender;
@end
Implementation (QuizAppDelegate.m):
init: Call super init, then allocate and initializequestionsandanswersasNSMutableArrayobjects. Populate them with questions and answers.showquestion:: Incrementcurrentquestionindex; if past the last question, wrap back to 0. Get the question string, log it, set thequestionfieldtext, and clear theanswerfield.showanswer:: Get the answer for the current index and set it as theanswerfieldtext.
๐ Example โ Implementation of the quiz controller:
@implementation QuizAppDelegate
- (id)init {
self = [super init];
if(self) {
questions = [[Nsmutablearray alloc] init];
answers = [[Nsmutablearray alloc] init];
[questions addobject:@"What is 7 + 7?"];
[answers addobject:@"14"];
[questions addobject:@"What is the capital of Vermont?"];
[answers addobject:@"Montpelier"];
[questions addobject:@"From what is cognac made?"];
[answers addobject:@"Grapes"];
}
return self;
}
- (IBAction)showquestion:(id)sender {
currentquestionindex++;
if (currentquestionindex == [questions count]) {
currentquestionindex = 0;
}
Nsstring *question = [questions objectatindex:currentquestionindex];
Nslog(@"displaying question: %@", question);
[questionfield settext:question];
[answerfield settext:@"???"];
}
- (IBAction)showanswer:(id)sender {
Nsstring *answer = [answers objectatindex:currentquestionindex];
[answerfield settext:answer];
}
@end
โญ Key Takeaways
Memory management in ObjectiveโC relies on manual reference counting: you own objects created with alloc/init/new/copy and must release them when done. For objects returned from other methods, you assume they are autoreleased; retain them if you need to keep them longer. The autorelease mechanism defers deallocation, simplifying memory management in return values. In iOS development, the MVC pattern structures apps into model, view, and controller layers. Interface Builder uses IBOutlet and IBAction to connect code to UI elements. The quiz app example demonstrates how to create a windowโbased app, connect buttons to actions, and manipulate labels programmatically.
๐ง Quick Revision Questions
- What is the retain count of an object immediately after
allocandinit? - When should you call
autoreleaseinstead ofrelease? - According to the memoryโmanagement rules, when do you own a returned object?
- What is the purpose of
IBOutletandIBActionin Xcode? - In the quiz app example, why is the
initmethod necessary, and what is the purpose of thecurrentquestionindexvariable?
๐ Lecture 43 โ Core Location Framework
๐ Overview: This lecture covers the Core Location framework for determining geographical position in iOS applications, building a "Where Am I" app. It introduces location managers, delegation patterns, map views, and annotations, demonstrating how to create location-aware iPhone applications.
๐๏ธ Topics Covered
Objective C memory management rules, writing a quiz app, xib and nib files, interface editor, MVC pattern, IBOutlet IBAction, Connection Inspector, init-showquestion-showanswer methods, Core Location Framework, CLLocationManager properties including distanceFilter and desiredAccuracy, delegation pattern, protocols, MKMapView for displaying maps, and MKAnnotation for adding location markers.
๐ Lecture Summary
Core Location Framework
The Core Location Framework provides classes for finding geographical position. Key properties include distanceFilter (minimum distance in meters before update is sent) and desiredAccuracy (how accurate the location reading should be). A CLLocationManager object is created to manage location services.
๐ Definition โ CLLocationManager: The object that starts and stops the delivery of location-related events to your app.
๐ Formula: distanceFilter = kCLDistanceFilterNone โ no minimum distance threshold for updates
๐ Formula: desiredAccuracy = kCLLocationAccuracyBest โ highest possible accuracy regardless of power/time
๐ Example: Creating and configuring a location manager:
locationmanager = [[CLLocationManager alloc] init];
[locationmanager setDistanceFilter:kCLDistanceFilterNone];
[locationmanager setDesiredAccuracy:kCLLocationAccuracyBest];
[locationmanager startUpdatingLocation];
Delegation Pattern
Delegation is a design pattern and an object-oriented approach to callbacks. It allows callback methods to share data between objects. A delegate can only be sent messages specified in its protocol. For every object that can have a delegate, there is a corresponding protocol (@protocol).
๐ Definition โ Delegate: An object that acts on behalf of another object, receiving messages when events occur.
The location manager sends messages to its delegate:
locationManager:didUpdateToLocation:fromLocation:- sent when new location data arriveslocationManager:didFailWithError:- sent when location cannot be found
๐ Example: Implementing delegate methods:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(@"%@", newLocation);
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(@"Could not find location: %@", error);
}
๐ก Why this matters: Delegation allows one object to handle events from another without tight coupling, enabling reusable components.
Protocols
Protocols are like interfaces in other languages - they contain no implementation. Protocols for delegation are called delegate protocols. Methods can be marked as @optional (not required to implement) or @required (must implement). By default, methods are required.
๐ Definition โ Protocol (@protocol): A list of method declarations that can be adopted by a class.
Key points:
respondsToSelector:checks if an object implements a specific method- Classes must declare protocols they implement in their interface declaration
๐ Example: Protocol declaration and checking:
if ([[self delegate] respondsToSelector:updateMethod]) {
[[self delegate] locationManager:self didUpdateToLocation:newLocation fromLocation:oldLocation];
}
Memory and Delegation
Delegates are never retained to avoid retain cycles. The delegate property uses the assign attribute (weak reference) instead of retain or strong.
๐ Definition โ Retain cycle: A situation where two objects hold strong references to each other, preventing either from being deallocated.
๐ Example: Proper memory management with delegates:
- (void)dealloc {
if ([locationManager delegate] == self) {
[locationManager setDelegate:nil];
}
[locationManager release];
[window release];
[super dealloc];
}
Displaying a Map with MKMapView
An MKMapView displays the map and labels for recorded locations. Key visual elements include:
- MKAnnotationView - appears as icons on the map
- UIActivityIndicatorView - indicates the device is working
- UITextField - allows user input to label locations
To show user location on the map, set the showsUserLocation property to YES on the MKMapView.
๐ Example: Setting up map view with user location:
[worldView setShowsUserLocation:YES];
Map View Delegate and Region Zooming
The MKMapViewDelegate protocol provides methods for map events. mapView:didUpdateUserLocation: is called when the user's location updates. To zoom the map, create an MKCoordinateRegion with a center coordinate and span in meters.
๐ Definition โ MKCoordinateRegionMakeWithDistance: Creates a coordinate region centered on a point with specified width and height in meters.
๐ Example: Zooming to user location:
- (void)mapView:(MKMapView *)mv didUpdateUserLocation:(MKUserLocation *)u {
CLLocationCoordinate2D loc = [u coordinate];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(loc, 250, 250);
[worldView setRegion:region animated:YES];
}
MKAnnotation Protocol and MapPoint Class
The MKAnnotation protocol provides an interface for annotating the map. A custom class (MapPoint) conforms to this protocol with required properties like coordinate and optional properties like title.
๐ Definition โ MKAnnotation: A protocol for objects that can be displayed as annotations on a map view.
๐ Example: Creating a custom annotation class:
@interface MapPoint : NSObject <MKAnnotation> {
NSString *title;
CLLocationCoordinate2D coordinate;
}
- (id)initWithCoordinate:(CLLocationCoordinate2D)c title:(NSString *)t;
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@end
Adding Annotations and Location Finding
The complete workflow for adding a location annotation involves:
- Finding location using CLLocationManager
- Creating a MapPoint with coordinates and title
- Adding the annotation to the MKMapView
- Cleaning up allocations
๐ Example: Complete location finding and annotation:
- (void)foundLocation:(CLLocation *)loc {
CLLocationCoordinate2D coord = [loc coordinate];
MapPoint *mp = [[MapPoint alloc] initWithCoordinate:coord
title:[locationTitleField text]];
[worldView addAnnotation:mp];
[mp release];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(coord, 250, 250);
[worldView setRegion:region animated:YES];
[locationTitleField setText:@""];
[activityIndicator stopAnimating];
[locationTitleField setHidden:NO];
[locationManager stopUpdatingLocation];
}
Handling Cached Location Data
CLLocationManager may return cached location data from previous sessions. To filter this out, check the timestamp property of the location and ignore data older than a threshold (e.g., 3 minutes = -180 seconds).
๐ Example: Filtering cached location data:
NSTimeInterval t = [[newLocation timestamp] timeIntervalSinceNow];
if (t < -180) {
// This is cached data, keep looking
return;
}
[self foundLocation:newLocation];
โญ Key Takeaways
Core Location provides CLLocationManager for geographical positioning with distanceFilter and desiredAccuracy properties controlling update frequency and precision. The delegation pattern is central to iOS development, where delegates receive callback messages like didUpdateToLocation and didFailWithError through protocols that define optional and required methods. Memory management requires delegates to use weak references (assign) to avoid retain cycles, and the delegate should be set to nil before release. The MKMapView displays maps and can show user location via the showsUserLocation property, with region zooming through MKCoordinateRegionMakeWithDistance. Custom annotations conform to the MKAnnotation protocol with required coordinate property and optional title, and location timestamps must be checked to filter out old cached data (typically ignoring locations older than 3 minutes).
๐ง Quick Revision Questions
- What are the two key properties of CLLocationManager that control how frequently location updates are received?
- Why must delegates use weak references (assign) rather than strong references (retain)?
- How do you check if a delegate implements a particular method before calling it?
- What is the purpose of checking the timestamp when receiving new location data from CLLocationManager?
- Which two protocols must a class adopt to both receive location updates and act as a map view delegate?
๐ Lecture 44 โ Touch Events, Drawing App, Blocks & GCD
๐ Overview: This lecture covers touch event handling for iOS mobile devices, demonstrating how to build a drawing app using touch event methods. It then introduces Blocks (anonymous functions) in Objective-C for dynamic color computation, and Grand Central Dispatch (GCD) for concurrent programming and thread management.
๐๏ธ Topics Covered
Touch events (began, moved, ended, cancelled) and UITouch objects; building a drawing app with Line model and TouchDrawView; handling single and multi-touch, double tap, and memory management; using Blocks for dynamic color calculation based on line angle and length; motion event handling for shake gesture; Grand Central Dispatch (GCD) for thread pools and concurrent execution; callback to UI thread using dispatch_async.
๐ Lecture Summary
Touch Events
Touch events are the hallmark of mobile devices. A finger or fingers touching the screen triggers touchesBegan:withEvent:. When a finger moves across the screen, touchesMoved:withEvent: is sent repeatedly. When a finger is removed, touchesEnded:withEvent: is called. If a system event (like an incoming phone call) interrupts a touch before it ends, touchesCancelled:withEvent: fires.
Events are added to the event queue. A UITouch object is created and tracked for each finger. A set of UITouches is passed โ one per finger. Only the moving, beginning, or ending event is passed.
๐ก Why this matters: Understanding the touch event lifecycle is fundamental for building interactive mobile applications.
Building the Drawing App โ Data Model
The Line class stores two CGPoint values: begin and end, representing the start and end points of a drawn stroke.
@interface Line: NSObject{
CGPoint begin;
CGPoint end;
}
@property (nonatomic) CGPoint begin;
@property (nonatomic) CGPoint end;
@end
Building the Drawing App โ TouchDrawView
The TouchDrawView is a UIView subclass that manages drawing. It has two collections:
- linesInProcess (NSMutableDictionary): maps UITouch keys to currently being drawn lines
- completeLines (NSMutableArray): stores finished lines
In initWithCoder:, both collections are allocated and setMultipleTouchEnabled:YES enables multi-touch support.
In clearAll, both collections are cleared and setNeedsDisplay triggers a redraw.
The drawRect: method uses UIGraphicsGetCurrentContext() to get the graphics context, sets line width to 10.0 and line cap to kCGLineCapRound. Complete lines are drawn in black; lines in process are drawn in red.
Touch Event Handling in the Drawing App
In touchesBegan:withEvent:, for each UITouch:
- If
[t tapCount] > 1(double tap),clearAllis called and method returns - The touch object is wrapped in an
NSValueto use as dictionary key - A new Line is created with
beginandendboth set to the touch location - The line is added to
linesInProcess
โ ๏ธ Note: There is a memory leak in this method (to be found using Instruments in next chapter).
In touchesMoved:withEvent:, for each touch, the corresponding lineโs end point is updated to the new location, then setNeedsDisplay redraws.
In touchesEnded:withEvent: and touchesCancelled:withEvent:, both call endTouches: helper method.
The endTouches: method:
- For each touch, retrieves the line from
linesInProcess - If line exists (not nil from double tap), adds it to
completeLinesand removes fromlinesInProcess - Calls
setNeedsDisplay
Using Blocks for Dynamic Colors
The Line class is extended with a *UIColor color property. In drawRect:, instead of using a fixed color, the code calls [[line color] set] for complete lines.
The method transformLineColorsWithBlock: takes a block parameter (UIColor* (^)(Line *))colorForLine. It iterates over completeLines, calls the block to compute a color, and sets it on each line.
The colorize method creates a block variable named colorScheme:
UIColor* (^colorScheme)(Line *) = ^(Line *l){
float dx = [l end].x - [l begin].x;
float dy = [l end].y - [l begin].y;
// If dx is near zero, red = 1.0, otherwise use slope
float r = (fabs(dx) < 0.001 ? 1.0 : fabs(dy/dx));
// If dy is near zero, green = 1.0, otherwise use inverse slope
float g = (fabs(dy) < 0.001 ? 1.0 : fabs(dx/dy));
// blue = length over 300
float b = hypot(dx, dy) / 300.0;
return [UIColor colorWithRed:r green:g blue:b alpha:1];
};
[self transformLineColorsWithBlock:colorScheme];
๐ Block โ An anonymous function in Objective-C that captures variables by value, similar to anonymous functions in C#. Blocks are an alternative to callbacks and are used with GCD.
Shake Gesture โ Motion Events
To respond to shaking:
- Override
canBecomeFirstResponderto returnYES - In
didMoveToWindow, call[self becomeFirstResponder] - Override
motionBegan:withEvent:to call[self colorize]
Grand Central Dispatch (GCD)
GCD is a technology for managing concurrent code execution using dispatch queues โ pools of threads managed by the system. Blocks are used with GCD for task-like execution.
Traditional threading using NSThread:
- (void) calculationThreadEntry{
@autoreleasepool {
NSUInteger counter = 0;
while ([[NSThread currentThread] isCancelled] == NO){
[self doCalculation];
counter++;
if (counter >= 1000) break;
}
}
}
- (BOOL)application:didFinishLaunchingWithOptions: {
[NSThread detachNewThreadSelector:@selector(calculationThreadEntry)
toTarget:self
withObject:nil];
// ...
}
Calling back on UI thread with GCD:
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^(void) {
[[[UIAlertView alloc] initWithTitle:@"GCD"
message:@"GCD is amazing!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil, nil] show];
});
Using concurrent queue with synchronous dispatch:
void (^printFrom1To1000)(void) = ^{
NSUInteger counter = 0;
for (counter = 1; counter <= 1000; counter++){
NSLog(@"Counter = %lu - Thread = %@",
(unsigned long)counter,
[NSThread currentThread]);
}
};
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(concurrentQueue, printFrom1To1000);
dispatch_sync(concurrentQueue, printFrom1To1000);
๐ dispatch_async โ Schedules a block for asynchronous execution on a dispatch queue (returns immediately). ๐ dispatch_sync โ Schedules a block for synchronous execution on a dispatch queue (waits until block completes). ๐ dispatch_get_main_queue() โ Returns the serial dispatch queue associated with the applicationโs main thread. ๐ dispatch_get_global_queue() โ Returns a concurrent dispatch queue with specified priority.
โญ Key Takeaways
Touch events form the foundation of mobile interaction; the four touch methods (began, moved, ended, cancelled) must be understood to handle user input properly. The drawing app demonstrates how to manage touch state using a dictionary for in-progress lines and an array for completed lines, with memory management being a critical concern. Blocks provide a powerful way to encapsulate functional behavior, such as dynamic color computation based on geometric properties of lines. GCD offers a clean, block-based API for concurrent programming, replacing traditional threading with dispatch queues. Finally, always update UI on the main thread using dispatch_async(dispatch_get_main_queue(), ^{...}) to avoid crashes and unpredictable behavior.
๐ง Quick Revision Questions
- What are the four touch event methods and when is each called?
- How does the drawing app distinguish between lines that are currently being drawn and completed lines?
- Why is the touch object wrapped in an NSValue when used as a dictionary key?
- In the
colorizemethod, how is the red, green, and blue component computed based on line geometry? - What is the difference between
dispatch_asyncanddispatch_syncwhen working with GCD queues?
๐ Lecture 45 โ Let's download an image asynchronously.
๐ Overview: This lecture demonstrates asynchronous image downloading using Grand Central Dispatch (GCD) in iOS development. It covers thread management, concurrent queues, and UI updates, followed by generating, storing, sorting random numbers, and a comprehensive course review.
๐๏ธ Topics Covered
The lecture covers asynchronous image downloading with dispatch queues, concurrent and main queue synchronization, file management for storing random numbers, generating 10,000 random numbers, sorting them using blocks, and concludes with a full course overview spanning from C++ message loops through C#, WPF, XAML, threading, JavaScript, jQuery, Ajax, JSON, and Objective-C.
๐ Lecture Summary
Let's download an image asynchronously.
The lecture begins by demonstrating how to download an image asynchronously using Grand Central Dispatch (GCD). This approach prevents the user interface from freezing during network operations.
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
The code creates a concurrent queue with default priority. Inside a dispatch_async block, it creates a __block UIImage variable. A dispatch_sync on the concurrent queue handles the actual download using NSURLConnection to fetch image data from Apple's website. After downloading, another dispatch_sync on the main queue (dispatch_get_main_queue()) updates the UI by creating a UIImageView and adding it to the view controller's view.
๐ Definition โ dispatch_async: Submits a block for asynchronous execution on a dispatch queue, returning immediately without waiting for the block to complete.
๐ Definition โ dispatch_sync: Submits a block for synchronous execution on a dispatch queue, blocking the current thread until the block completes.
๐ Formula/Pattern: dispatch_async(background_queue, ^{ dispatch_sync(background_queue, { /* work */ }); dispatch_sync(main_queue, { /* update UI */ }); });
๐ Example: The code downloads an iPad image from http://images.apple.com/mobileme/features/images/ipad_findyouripad_20100518.jpg. It creates an NSURL from the string, sends a synchronous request using [NSURLConnection sendSynchronousRequest:], and stores the data as a UIImage. On the main queue, it creates a UIImageView with the downloaded image and adds it to self.view.
๐ก Why this matters: This pattern ensures network operations don't block the UI thread, while all UI updates happen safely on the main thread.
Generate 10k random numbers if needed. Read 10K random numbers, sort and display. UITableView.
This section demonstrates file management and data processing using GCD. The fileLocation method creates a path in the documents directory for a file named list.txt. The hasFileAlreadyBeenCreated method checks if this file exists using NSFileManager.
- (NSString *) fileLocation {
NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([folders count] == 0) { return nil; }
NSString *documentsFolder = [folders objectAtIndex:0];
return [documentsFolder stringByAppendingPathComponent:@"list.txt"];
}
Inside a dispatch_async block on the concurrent queue, the code checks if the file exists. If not, it generates 10,000 random numbers using arc4random(), stores them in an NSMutableArray, and writes the array to disk using writeToFile:atomically:. A subsequent dispatch_sync reads the file, loads the array, and sorts it in ascending order using sortUsingComparator: with a block that compares NSNumber objects using compare:.
๐ Definition โ arc4random: A function that generates cryptographically secure random numbers, returning an unsigned integer.
๐ Definition โ sortUsingComparator: An NSMutableArray method that sorts elements using a block that returns an NSComparisonResult.
๐ Example: The code generates 10,000 random numbers using arc4random() % ((unsigned int)RAND_MAX + 1), wraps each in [NSNumber numberWithUnsignedInt:], and stores them in an array. It writes this array to list.txt. Later, it reads the file with initWithContentsOfFile:, then sorts using [randomNumbers sortUsingComparator:^NSComparisonResult(id obj1, id obj2) { return [((NSNumber *)obj1) compare:((NSNumber *)obj2)]; }].
Dispatch after dispatches after a delay. Timers. Dependencies. Group of tasks.
This section briefly mentions additional GCD features including dispatch_after (for delayed execution), timers, dependencies between blocks, and dispatch groups for managing task groups.
Course Overview: Where did we start from. Where to go from here.
The course overview summarizes the entire semester, covering:
- Started with handling multiple input sources in C++, message loop refactoring, events, event processing, source/target/event object, Visual Studio and C# language features, OOP examples in C#
- Discussed delegates, events, exception handling, attributes, collections, XML documents, WPF history and XAML, property elements and markup extensions, mixing XAML and procedural code
- Discussed logical and visual trees, dependency properties, change notifications, property value inheritance, attached properties, sizing/positioning/transforming elements
- Discussed transforms, panels (StackPanel, WrapPanel, Canvas, DockPanel, Grid), content overflow, clipping, scaling, scrolling
- Discussed events, input events, attached events, touch events (manipulation - high level), commands, persisting and restoring
- Covered resources (binary and logical, static vs dynamic), data binding (binding object, binding markup extension, binding to collections, implicit DataContext), DataTemplates and value converters, customizing collection view (sorting, filtering, grouping, navigating), data providers (XML and Object Data Providers)
- Concurrency and threads, captured variables, synchronization context and tasks, continuations, task completion source, sync vs async
- Coarse-grained vs fine-grained sync, async/await keywords in C# 5.0, parallelism, cancellation and progress reporting, task combinators and Task Parallel Library (Parallel.Invoke, For, ForEach), concurrent collections
- JavaScript history and jQuery library, HTML/CSS/JS, client-side vs server-side, DOM, jQuery selectors and filters, changing attributes and elements, events and animations, Ajax, XMLHttpRequest (GET PUT LOAD), JSON
- Mobile development, Objective-C history, call syntax and OO concepts, properties, retain count and memory management, Xib/Nib, IBOutlet, IBAction, Interface Builder
- Button events and a QA app, protocols and delegates, location and map kits, touch events and blocks, GCD and multithreading
โญ Key Takeaways
- Always perform network operations (like image downloading) on a background concurrent queue using
dispatch_asyncto avoid blocking the UI, then update the UI on the main queue usingdispatch_syncordispatch_async. - When downloading data, create
__blockvariables to make them mutable inside block contexts, and always handle error cases (no data, download error, successful data). - For file persistence, use
NSSearchPathForDirectoriesInDomainsto get the documents directory, and usewriteToFile:atomically:for saving arrays andinitWithContentsOfFile:for reading them. - Sort collections using
sortUsingComparator:with block-based comparison logic, and usearc4random()for generating random numbers in Objective-C. - The course progression goes from C++ fundamentals through C#/WPF/XRML, threading/async patterns, JavaScript/jQuery/Ajax, to Objective-C/iOS development with GCD for multithreading.
๐ง Quick Revision Questions
- Why must you use
dispatch_sync(dispatch_get_main_queue(), ...)when updating the UI after an asynchronous download? - What is the purpose of the
__blockstorage qualifier in the image downloading example? - How does the code determine whether it needs to generate new random numbers or read existing ones from disk?
- What method is used to sort the random numbers array, and how does the comparator block work?
- List three GCD features mentioned beyond
dispatch_asyncanddispatch_sync.