Objective-C ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Similar documents
Objective-C and COCOA Applications

Sorting. Sorting. 2501ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Object Oriented Programming in C++

Collections & Memory Management. Lecture 2

Mobile Application Programming. Objective-C Classes

Mobile Application Development

Objective-C Part 2 (ECS189H) Ken Joy Serban Porumbescu

Abstract Data Types. 2501ICT/7421ICTNathan. René Hexel. Semester 1, School of Information and Communication Technology Griffith University

Collections. Fall, Prof. Massimiliano "Max" Pala

Review (Basic Objective-C)

ios: Objective-C Primer

Design Phase. Create a class Person. Determine the superclass. NSObject (in this case)

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

Announcement. Final Project Proposal Presentations and Updates

ITP 342 Advanced Mobile App Dev. Memory

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties

Principles of Programming Languages. Objective-C. Joris Kluivers

CS 47. Beginning iphone Application Development

Praktikum Entwicklung von Mediensystemen mit ios

Jython. An introduction by Thinh Le

Objective-C. Stanford CS193p Fall 2013

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

ITP 342 Mobile App Dev. Fundamentals

Homework 4. Any questions?

Intro to Native ios Development. Dave Koziol Arbormoon Software, Inc.

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

Memory Management: The Details

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Advanced Object- C Features

Mobile Application Development

COCOA WORKSHOP PART 1. Andreas Monitzer

Data Management: Event Handling

ios Development Lecture 1 Introduction to Objective-C Ing. Simone Cirani

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013

Introductory ios Development

src7-malan/c/array/array/main.c // main.c // Array // David J. Malan // Harvard University // // Demonstrates arrays. 11.

the gamedesigninitiative at cornell university Lecture 9 Memory Management

OBJECTIVE-C BEST PRACTICES IN A TEAM ENVIRONMENT

This reference will take you through simple and practical approach while learning Objective-C Programming language.

CS193p Spring 2010 Thursday, April 29, 2010

Mobile Application Development

Working Effectively with Objective-C on iphone OS. Blaine Garst Wizard of Runtimes

Cocoa Programming. David Chisnall. March 18,

Chapter 11. Abstract Data Types and Encapsulation Concepts

iphone OS Overview

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import "Deck.

Abstract data types &

Abstract Data Types & Object-Oriented Programming

Chapter 11. Abstract Data Types and Encapsulation Concepts

iphone Programming Patrick H. Madden SUNY Binghamton Computer Science Department

Esri Developer Summit in Europe ArcGIS Runtime for ios

For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C?

CS2141 Software Development using C/C++ C++ Basics

Array Initialization

Getting Started with ArcGIS Runtime SDK for ios. Nick Furness / Al Pascual

src2/section2.0/section2/main.m // main.m // Students7 // David J. Malan // Harvard University // // Demonstrates mutable arrays.

1.The basics 5 Comments 5 Variables and basic types 6 Operators 8 Object variables 10 A note on prefixes and namespaces 11

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

PROGRAMMAZIONE I A.A. 2017/2018

COMP327 Mobile Computing Session: Tutorial Objective-C and the Foundation Framework

More Programming Languages. Spring 2014 Carola Wenk

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

Lecture 27. Log into Windows/ACENET. Start MS VS and open the PointClassDemo project. Reminder: Project 1 is due on Wednesday. Questions?

C++ Programming Fundamentals

Contents at a Glance

COMP 2355 Introduction to Systems Programming

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

Accustoming Yourself to Objective-C

By Ryan Hodson. Foreword by Daniel Jebaraj

Introduction to ArcGIS API for ios. Divesh Goyal Eric Ito

Object-Oriented Programming with Objective-C. Lecture 2

CA341 - Comparative Programming Languages

ios Development A Practical Approach Nicolaas tenbroek

Announcements. CSCI 334: Principles of Programming Languages. Lecture 18: C/C++ Announcements. Announcements. Instructor: Dan Barowy

Praktikum Entwicklung von Mediensystemen mit

CS349/SE382 A1 C Programming Tutorial

Data Management

Grade Weights. Language Design and Overview of COOL. CS143 Lecture 2. Programming Language Economics 101. Lecture Outline

A little more Core Data

Common Misunderstandings from Exam 1 Material

Pointers. Pointers. Pointers (cont) CS 217

Multitasking and Background Execution

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 371L - Mobile Computing (ios) Dr. William C. Bulko. CS 371L Mobile Computing (ios) Introduction

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Garbage Collection. CS 351: Systems Programming Michael Saelee

IPHONE. Development Jump Start. phil nash levelofindirection.com

FINAL TERM EXAMINATION SPRING 2010 CS304- OBJECT ORIENTED PROGRAMMING

The University of Nottingham

About MSDOSX. Lecture 0

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

iphone Programming Touch, Sound, and More! Norman McEntire Founder Servin Flashlight CodeTour TouchCount CodeTour

Transcription:

Objective-C 2.0 2501ICT/7421ICTNathan René Hexel School of Information and Communication Technology Griffith University Semester 1, 2012

Outline Fast Enumeration and Properties 1 Fast Enumeration and Properties For Each Loops Properties 2 Native 3 Using Blocks Garbage Collection and ARC

Objective-C 2.0 Objective-C 2.0

Remember Enumerators? For Each Loops Properties NSEnumerator handles enumeration in an object-oriented way Example (Enumerators using NSEnumerator) #import <Foundation/Foundation.h> int main(int argc, char *argv[]) NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *list = [NSArray arraywithobjects: @"1", @"2", @"3", nil]; NSEnumerator *enumerator = [list objectenumerator]; NSString *s; while (s = [enumerator nextobject]) printf("%s ", [s UTF8String]); // loop through array // print each element printf("\n"); [pool release]; return EXIT_SUCCESS;

For Each Loops Properties For Each Loops in Objective-C 2.0 New Language feature: for(object in collection) uses fast enumeration Example (Fast Enumeration) #import <Foundation/Foundation.h> int main(int argc, char *argv[]) NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *list = [NSArray arraywithobjects: @"1", @"2", @"3", nil]; for (NSString *s in list) printf("%s ", [s UTF8String]); // fast enumeration // print each element printf("\n"); [pool release]; return EXIT_SUCCESS;

Access Methods Reviewed For Each Loops Properties Every object property should have two access methods Setters and Getters Example (Point2D.h with access methods) #import <Foundation/Foundation.h> @interface Point2D: NSObject int x; int y; - (int) x; // access methods - (void) setx: (int) newx; - (int) y; - (void) sety: (int) newy; @end

Access Methods Reviewed For Each Loops Properties Every object property should have two access methods Setters and Getters Example (Point2D.m with access methods) #import "Point2D.h" @implementation Point2D - (int) x return x; - (void) setx: (int) newx x = newx; - (int) y return y; - (void) sety: (int) newy y = newy; @end

Objective-C 2.0 Properties For Each Loops Properties @property declares class properties

Objective-C 2.0 Properties For Each Loops Properties @synthesize creates code for setters and getters automatically!

For Each Loops Properties Using Objective-C 2.0 Properties Normal set and get methods can be used properties stick to standard naming conventions! Point2DMain #import "Point2D.h" int main(int argc, char *argv[]) Point2D *pt = [Point2D new]; with dot notation #import "Point2D.h" int main(int argc, char *argv[]) Point2D *pt = [Point2D new]; [pt setx: 5]; pt.x = 5; // invokes setx: printf("x = %d\n", [pt x]); return EXIT_SUCCESS; printf("x = %d\n", pt.x); return EXIT_SUCCESS;

Properties Summarised For Each Loops Properties @property defines a property needs a storage type! assign for a simple assignment (e.g. int) retain for retaining Objects (release and retain) copy for copying Objects (e.g. NSString) Other qualifiers: readonly, readwrite, nonatomic @synthesize creates getter and setter code in.m file Dot notation: syntactic sugar for invoking setters and getters, e.g.: int x = point.x; for int x = [point x]; point.x = x; for [point setx: x]; point.x++; for [point setx: [point x] + 1];

Native in Objective-C 2.0 @try starts an exception handling domain like try in Java replaces older NS_DURING macro exceptions that occur will be caught @catch (NSException *localexception) the actual exception handler catches exceptions that occur in the handling domain replaces older NS_HANDLER macro @finally follows both normal and abnormal termination replaces older NS_ENDHANDLER macro

Native Objective-C 2.0 Example Example (NSRangeException) #import <Foundation/Foundation.h> int main(int argc, char *argv[]) NSAutoreleasePool *pool = [NSAutoreleasePool new]; NSArray *array = [NSArray array]; // an empty array @try id object = [array objectatindex: 0]; // will this work? printf("%s", [object UTF8String]); // never reached @catch (NSException *localexception) printf("%s: %s", [[localexception name] UTF8String], // print exception [[localexception reason] UTF8String]); // and reason @finally printf(", count = %lu\n", [array count]); [pool release]; return EXIT_SUCCESS;

Native Objective-C 2.0 Exception Throwing Example Example (prints: MyException: reason 42) #import <Foundation/Foundation.h> void some_function(void) [NSException raise: @"MyException" // raise MyException format: @"reason %d", 42]; // a not very readable reason! int main(int argc, char *argv[]) NSAutoreleasePool *pool = [NSAutoreleasePool new]; @try some_function(); // call some function @catch (NSException *localexception) printf("%s: %s\n", [[localexception name] UTF8String], [[localexception reason] UTF8String]); [pool release]; return EXIT_SUCCESS;

Blocks Fast Enumeration and Properties Using Blocks Garbage Collection and ARC C Functions can be useful, but have drawbacks global namespace (e.g. only one main() function module-specific static functions still requires separate definition and naming Blocks allow defining functions on the fly syntax addition at the C Language level can vastly simplify code very powerful lambda expressions

Simple Block Example Using Blocks Garbage Collection and ARC Blocks are defined using ˆ... Example (Passing a Block to a Method) MyClass *myobject = [[MyClass alloc] init]; [myobject dosomethingusingblock: ^ /*... some code */ ];

Block Parameter Example Using Blocks Garbage Collection and ARC Blocks can take parameters (like functions) Example (Block Enumeration in NSArray) NSArray *array = [NSArray arraywithobjects: @"1", @"2", @"3", nil]; [array enumerateobjectsusingblock: ^(id obj, NSUInteger i, BOOL *stop) NSLog(@"String at Index %d is %@", i, obj); if (i == 1) *stop = YES; // stop enumeration ];

Passing local Variables to Blocks Using Blocks Garbage Collection and ARC Local Variables declared outside can be used within blocks Inside the block, these variables are read only! But: instance variables can be modified!

Read/Write Block Variables Using Blocks Garbage Collection and ARC Local Variables can be declared as block to be writable Example (Read/Write variable used inside block) NSArray *array = [NSArray arraywithobjects: @"1", @"2", @"3", nil]; block int count = 0; [array enumerateobjectsusingblock: count++; ]; ^(id obj, NSUInteger i, BOOL *stop) // increment count printf("count is %d\n", count);

Garbage Collection Using Blocks Garbage Collection and ARC Normally Objective-C uses reference counting, i.e. reference count gets set to 1 by new, alloc, and copy incremented by retain decremented by release (calls dealloc if 0) Garbage Collection is available for Objective-C 2.0 Mac OS X 10.5 (or above) only! not on GNUstep not on the iphone! Optimising Code for Garbage Collection: Autorelease Pools use [pool drain] instead of [pool release]

Automatic Reference Counting Using Blocks Garbage Collection and ARC The latest clang Objective-C compiler knows Memory Management Rules Programmer must still make explicit what kind of reference each pointer is! strong properties are retained and released weak properties are zeroed out on dealloc Normal pointers also need to indicate their ownership Language extension introduced by clang Must be specified if the compiler cannot determine ownership strong weak unsafe_unretained (not handled by compiler) autoreleasing (put on autorelease pool)

Autorelease Pools Revisited Using Blocks Garbage Collection and ARC @autoreleasepool... Compiler Support for Autorelease Pools faster than NSAutoreleasePool works for ARC and non-arc code as well as Garbage Collection Example (Using @autoreleasepool) #import <Foundation/Foundation.h> int main(int argc, char *argv[]) @autoreleasepool NSArray *list = [NSArray arraywithobjects: for (NSString *s in list) printf("%s ", [s UTF8String]); @"1", @"2", @"3", nil]; // fast enumeration // print each element printf("\n"); return EXIT_SUCCESS;