A little more Core Data

Size: px
Start display at page:

Download "A little more Core Data"

Transcription

1 A little more Core Data

2 A little more Core Data NSFetchedResultsController Interacts with the Core Data database on your behalf [fetchedresultscontroller objectatindexpath:] gets at row data [fetchedresultscontroller sections] gets at section data

3 A little more Core Data NSFetchedResultsController Interacts with the Core Data database on your behalf [fetchedresultscontroller objectatindexpath:] gets at row data [fetchedresultscontroller sections] gets at section data NSFetchedResultsSectionInfo Protocol defining methods that you can call from your UITableViewDataSource methods numberofsectionsintableview: tableview:numberofrowsinsection: tableview:cellforrowatindexpath:

4 iphone Performance Overview

5 iphone Performance Overview iphone applications must work with... Limited memory Slow or unavailable network resources Less powerful hardware

6 iphone Performance Overview iphone applications must work with... Limited memory Slow or unavailable network resources Less powerful hardware Write your code with these constraints in mind

7 iphone Performance Overview iphone applications must work with... Limited memory Slow or unavailable network resources Less powerful hardware Write your code with these constraints in mind Use performance tools to figure out where to invest

8 Memory Usage

9 Memory Management CPRE 388

10 Fundamental Memory Management Rules You only release or autorelease objects you own. You take ownership of an object if you create it using a method whose name begins with alloc or new or contains copy (for example, alloc, newobject, or mutablecopy), or if you send it a retain message. You use release or autorelease to relinquish ownership of an object. autorelease just means send a release message in the future

11 Corollaries to the Fundamental rule if you need to store a received object as a property in an instance variable, you must retain or copy it. A received object is normally guaranteed to remain valid within the method it was received in, and that method may also safely return the object to its invoker. Exceptions include multithreaded applications. Use retain in combination with release or autorelease when needed to prevent an object from being invalidated as a normal side effect of a message.

12 Object Ownership Policy object may have one or more owner. As long as an object has at least one owner, it continues to exist. If an object has no owners, the runtime system destroys it automatically You own any object you create You can take ownership of an objectusing retain You must relinquish (release) ownership of objects you own when you re finished with them You must not relinquish ownership of an object you do not own

13 { Thingamajig *mythingamajig = [[Thingamajig alloc] init]; //... NSArray *sprockets = [mythingamajig sprockets]; //... [mythingamajig release];

14 Recap retain count When you create an object, it has a retain count of 1. When you send an object a retain message, its retain count is incremented by 1. When you send an object a release message, its retain count is decremented by 1. When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. If an object s retain count is reduced to 0, it is deallocated

15 Correctly autoreleased (NSArray *)sprockets { NSArray *array = [[NSArray alloc] initwithobjects:mainsprocket, auxiliarysprocket, nil]; return [array autorelease];

16 Recap wrong release (NSArray*)sprockets{ NSArray *array = [[NSArray alloc] initwithobjects:mainsprocket, auxiliarysprocket, nil]; return array; After the method returns, the object loses its reference to the new object so cannot relinquish ownership caller is given no indication that it owns the returned object

17 Recap wrong release (NSArray *)sprockets { NSArray *array = [[NSArray alloc] initwithobjects:mainsprocket, auxiliarysprocket, nil]; [array release]; return array; // array is invalid here

18 Correct method (NSArray *)sprockets { NSArray *array = [NSArray arraywithobjects:mainsprocket, auxiliarysprocket, nil]; return array; You don t own the array returned from arraywithobjects:, you are therefore not responsible for relinquishing ownership

19 Important: To understand this, it s tempting to think of the arraywithobjects: method itself being implemented using autorelease. Although correct in this case, it s strictly an implementation detail. Just as you shouldn t be concerned with an object s actual retain count, you shouldn t be concerned about whether an object returned to you is autoreleased or not. The only concern is, do you own it or not.

20 Validity of Shared Objects Cocoa s ownership policy specifies that received objectsshouldshould typically remain valid throughout the scope of the calling method It should also be possible to return a received object from the current scope without fear of it being released

21 Exceptions to the sharing rule When an object is removed from one of the fundamental collection classes: heisenobject = [array objectatindex:n]; [array removeobjectatindex:n]; // heisenobject could now be invalid. When an object is removed from one of the fundamental collection classes, it is sent a release (rather than autorelease) message. If the collection was the only owner of the removed object, the removed object (heisenobject in the example ) is then immediately deallocated.

22 Exception 2: When a parent object is deallocated: id parent = <#create a parent object#>; //... hi heisenobject = [parent child] ; [parent release]; // Or, for example: self.parent = nil; // heisenobject could now be invalid. In some situations you retrieve an object from anotherobject, object, thendirectly or indirectly release the parent object. If releasing the parent causes it to be deallocated, and the parent was the only owner of the child, then the child (heisenobject in the example) will be deallocated

23 Retain it heisenobject = [[array objectatindex:n] retain]; [array removeobjectatindex:n]; // use heisenobject. [heisenobject release];

24 Accessor methods If your class has an instance variable that is an object, you must make sure that any object that is set as the value for the instance variable is not freed while you re using it You must therefore claim ownership of the object when it is set. You must also make sure you then relinquish ownership of any currently held value.

25 (void)setmainsprocket:(sprocket *)newsprocket { [mainsprocket autorelease]; mainsprocket = [newsprocket retain]; /* Claim the new Sprocket. */ return;

26 (void)setmainsprocket:(sprocket ( p *)newsprocket { [mainsprocket autorelease]; mainsprocket = [newsprocket copy]; /* Make a private copy. */ return; If you do not wish to share a copy.

27 If newsprocket and mainsprocket are the same object & Thingamajig is the only object that owns it (void)setmainsprocket:(sprocket *)newsprocket { if (mainsprocket!= newsprocket) { [mainsprocket release]; mainsprocket = [newsprocket retain]; /* Or copy, if appropriate. */

28 Deallocation If your class has object instance variables that it owns, you must implement a dealloc method that releases them, and then invokes super s s implementation - (void)dealloc { [mainsprocket release]; [auxiliarysprocket release]; [super dealloc];

29 Dealloc Don ts You should never invoke another object s dealloc method directly You should not tie management of system resources to object lifetimes When an application terminates, objects may not be sent a dealloc message

30 Retain Cycles

31 Retain Cycles Parent objectsretain their children Children should not retain parents h hild f i i The child s reference to its parent is an example of a weak reference

32 Weak vs Strong reference Retaining an object creates a strong reference to that object. An object cannot be deallocated until all of its strong references are released. There is a connotation that the referee object s lifetime encircles the lifetime of referred objects. You may want to have a reference to an object without preventing the object from deallocating itself. For these cases, you can obtain a weak reference. A weak reference is created by storing a pointer to an object without retaining the object

33 Weak references Weak ref cases in Cocoa include, but are not restricted to, table data sources, outline view items, notificationobservers observers, andmiscellaneous targets and delegates. for example, an NSTableView object does not retain its data source and the NSApplication object does not retain its delegate You need to be careful about sending messages to objects for which you only hold a weak reference. If you send a message to an object after it has been deallocated, d your application will crash.

34 In most cases, the weak referenced object is aware of the other object s weak reference to it, as is the case for circular references, and is responsible for notifying the other object when it deallocates. For example, when you register an object with a notification center, the notification center stores a weak reference to the object and sends messages to it when the appropriate notificationsare are posted. When the object is deallocated, you need to unregister it with the notification center to prevent the notification center from sending any further messages to the object, which no longer exists. Likewise, when a delegate object is deallocated, you need to remove the delegate link by sending a setdelegate: message with a nil argument to the other object. These messages are normally sent from the object s dealloc method.

35 Practical memory management An object may have one or more owners. By way of an analogy, consider a timeshare apartment. When an object has no owners, it is destroyed. d To stretch the analogy, consider a timeshare complex that is not loved by the local population. If there are no owners, the complex will be torn down. To make sure an object you re interested in is not destroyed, you must become an owner. You can either build a new apartment, or take a stake in an existing one. To allow an object in which you re no longer interested to be destroyed, you relinquish ownership. You can sell your timeshare apartment

36 You only own objects you created using a method whose name begins with alloc or new or contains copy (for example, alloc, newobject, or mutablecopy), or if you send it a retain message. Many classes provide methods of the form +classname... that you can use to obtain a new instance of the class. Often referred to as convenience constructors, these methods create a new instance of the class, initialize it, and return it for you to use. You do not own objects returned from convenience constructors, or fromotheraccessor other methods

37 The first example creates a new string ti object using alloc. It must therefore be released. - (void)printhello { NSString *string; string = [[NSString alloc] initwithstring:@"hello"]; NSLog(string); [string release];

38 The second example creates a new string object using a convenience constructor. There is no additional work to do. - (void)printhello { NSString *string; string = [NSString stringwithformat:@"hello"]; NSLog(string); (ti

39 The third example retrieves a string object using an accessor method. As with the convenience constructor, there is no additional work to do. - (void)printwindowtitle { NSString *string; string = [mywindow title]; NSLog(string); g);

40 Using Accessor Methods Consider a Counter object whose count you want to Counter : NSObject { NSNumber *count; In the get accessor, you just pass back a variable so there is no need for retain or release: - (NSNumber *)count { return rn count;

41 Set accessor: Take ownership of new count. relinquish ownership of the old count - (void)setcount:(nsnumber ( *)newcount { [newcount retain]; [count release]; // make the new assignment count = newcount;

42 The only places you shouldn t use accessor methods to set an instance variable are in init methods and dealloc. To initialize a counter object with a number object representing zero - init { self = [super init]; if (self) { count = [[NSNumber alloc] initwithinteger:0]; return self;

43 To allow a counter to be initialized with a count other than zero, initwithcount: - initwithcount:(nsnumber *)startingcount { self = [super init]; if (self) { count = [startingcount copy]; return self;

44 Since the Counter class has an object instance variable, you must also implement a dealloc method. - (void)dealloc { [count release]; [super dealloc];

45 Reset method Uses a convenience constructor to create a new NSNumber object there is therefore no need for any retain or release - (void) reset { NSNumber *zero = [NSNumber numberwithinteger:0]; [self setcount:zero];

46 alloc and release - (void)reset { NSNumber *zero = [[NSNumber alloc] initwithinteger:0]; [self setcount:zero]; [zero release];

47 Accessor not used - (void)reset { Common Mistakes NSNumber *zero = [[NSNumber alloc] initwithinteger:0]; [count release]; count = zero;

48 Instance leaks - (void)reset { NSNumber *zero = [[NSNumber alloc] initwithinteger:0]; [self setcount:zero];

49 Instance you don t own is sent release - (void)reset { NSNumber *zero = [NSNumber numberwithinteger:0]; [self setcount:zero]; t [zero release];

50 Using Collections When you add an object to a collection such as an array, dictionary, i or set, the collection takes ownership of it. The collection will relinquish ownership when the object is removed from the collection or when the collection is itself released

51 No alloc, no retain! NSMutableArray *array; NSUInteger i; //... for (i = 0; i < 10; i++) { NSNumber *conveniencenumber = [NSNumber numberwithinteger:i]; [array addobject:conveniencenumber];

52 NSMutableArray *array; NSUInteger i; //... for (i = 0; i < 10; i++) { NSNumber *allocednumber = [[NSNumber alloc] initwithinteger: i]; [array addobject:allocednumber]; [allocednumber release];

53 Returning Objects from Methods When you return a local variable from a method: adhere to the memorymanagement management rules the receiver gets an opportunity to use the object before it s deallocated

54 - (NSString *)fullname { NSString *string = [NSString stringwithformat:@"%@ %@", firstname, lastname]; return string; you don t own the string returned by stringwithformat, so you can safely return it from the method

55 - (NSString *)fullname { NSString *string = [[[NSString alloc] initwithformat:@"%@ %@", firstname, lastname] autorelease]; return string;

56 - (NSString *)fullname { NSString *string = [[[NSString alloc] initwithformat:@"%@ %@", firstname, lastname] release]; return string;

57 (NSString *)fullname { NSString *string = [[NSString alloc] initwithformat:@"%@ %@", firstname, lastname]; return string;

58 Autorelease pools An autorelease pool is an instance of NSAutoreleasePool that contains other objects that have received an autorelease message Cocoa always expects there to be an autorelease pool available. create an NSAutoreleasePool object with the usual alloc and init messages, and dispose of it with drain Autorelease pools are stacked or nested.

59 void main() { NSAutoreleasePool l *pool = [[NSAutoreleasePool l alloc] init]; i NSArray *args = [[NSProcessInfo processinfo] arguments]; for (NSString *filename in args) { NSAutoreleasePool *looppool = [[NSAutoreleasePool alloc] init]; NSError *error = nil; NSString *filecontents = [[[NSString alloc] initwithcontentsoffile:filename encoding:nsutf8stringencoding error:&error] autorelease]; /* Process the string, creating and autoreleasing more objects. */ [looppool drain]; /* Do whatever cleanup is needed. */ [pool drain]; exit (EXIT_SUCCESS);

60 Scope of autorelease pools What if an objects needs to live past the scope of the current autorelease pool? (id)findmatchingobject:(id)anobject { id match = nil; while (match == nil) { NSAutoreleasePool *subpool = [[NSAutoreleasePool alloc] init]; i

61 /* Do a search that creates a lot of temporary objects. */ match = [self expensivesearchforobject:anobject]; if (match!= nil) { [match retain]; /* Keep match around. */ [subpool release]; return [match autorelease]; /* Let match go and return it. */

62 Implementing Accessor Methods Three ways to implement the accessors: 1. Getter retains and autoreleases the value before returning it; setter releases the old value and retains (or copies) the new value. 2. Getter returns the value; setter autoreleases the old value and retains (or copies) the new value. 3 Getter returns the value; setter releases the old 3. Getter returns the value; setter releases the old value and retains (or copies) the new value.

63 Technique 1 - (NSString*) title { return [[title retain] autorelease]; - (void) settitle: (NSString*) newtitle { if (title!= newtitle) { [title release]; title = [newtitle retain]; // Or copy, depending on your needs.

64 Object returned from the get accessor is autoreleased in the current scope, it remains valid if the property p value is changed. makes the accessor more robust, but at the cost of additional overhead If you expect your getter method to be called frequently, the added cost of retaining and autoreleasing the object may not be worth the performance cost.

65 Technique 2: - (NSString*) title { return title; - (void) settitle: (NSString*) newtitle { [title autorelease]; title = [newtitle retain]; // Or copy, depending on your needs. significantly better performance than technique 1 in situations ti where the getter is called much more often than the setter.

66 Technique 3: - (NSString*) title { return title; - (void) settitle: (NSString*) newtitle { if (newtitle!= title) { [title release]; title = [newtitle retain]; // Or copy, depending on your needs.

67 The approach used by technique 3 is good for frequently called getter and setter methods. It is also good for objects that do not want to extend the lifetime of their values, such as collection classes. Its disadvantage is that the old value may be deallocated immediately (if there are no other owners), which will cause a problem if another object is maintaining a non owning owning reference to it.

68 Memory on the iphone

69 Memory on the iphone Starting points for performance Load lazily Don t leak Watch your autorelease footprint Reuse memory

70 Memory on the iphone Starting points for performance Load lazily Don t leak Watch your autorelease footprint Reuse memory System memory warnings are a last resort Respond to warnings or be terminated

71 Loading Lazily Pervasive in Cocoa frameworks Do only as much work as is required Application launch time! Think about where your code really belongs Use multiple NIBs for your user interface

72 Loading a Resource Too Early

73 Loading a Resource Too Early What if it s not needed until much later? Or not at all? - (id)init { self = [super init]; if (self) { // Too early... myimage = [self readsomehugeimagefromdisk]; return self;

74 Loading a Resource Lazily

75 Loading a Resource Lazily Wait until someone actually requests it, then create it - (UIImage *)myimage { if (myimage == nil) { myimage = [self readsomehugeimagefromdisk];

76 Loading a Resource Lazily Wait until someone actually requests it, then create it - (UIImage *)myimage { if (myimage == nil) { myimage = [self readsomehugeimagefromdisk]; This pattern benefits both memory and launch time

77 Loading a Resource Lazily Wait until someone actually requests it, then create it - (UIImage *)myimage { if (myimage == nil) { myimage = [self readsomehugeimagefromdisk]; This pattern benefits both memory and launch time Not always the right move, consider your specific situation

78 Loading a Resource Lazily Wait until someone actually requests it, then create it - (UIImage *)myimage { if (myimage == nil) { myimage = [self readsomehugeimagefromdisk]; This pattern benefits both memory and launch time Not always the right move, consider your specific situation Notice that above implementation is not thread-safe!

79 Plugging Leaks

80 Plugging Leaks Memory leaks are very bad Especially in code that runs often

81 Plugging Leaks Memory leaks are very bad Especially in code that runs often Luckily, leaks are easy to find with the right tools

82 Method Naming and Object Ownership

83 Method Naming and Object Ownership If a method s name contains alloc, copy or new, then it returns a retained object

84 Method Naming and Object Ownership If a method s name contains alloc, copy or new, then it returns a retained object Balance calls to alloc, copy, new or retain with calls to release or autorelease

85 Method Naming and Object Ownership If a method s name contains alloc, copy or new, then it returns a retained object Balance calls to alloc, copy, new or retain with calls to release or autorelease Early returns can make this very difficult to do!

86 Finding Leaks Use Instruments with the Leaks recorder

87 Identifying Leaks in Instruments Each leak comes with a backtrace Leaks in system code do exist, but they re rare If you find one, tell us at Consider your own application code first

88 Caught in the Act

89 Autorelease and You

90 Autorelease and You Autorelease simplifies your code Worry less about the scope and lifetime of objects

91 Autorelease and You Autorelease simplifies your code Worry less about the scope and lifetime of objects When an autorelease pool is drained, it calls -release on each object

92 Autorelease and You Autorelease simplifies your code Worry less about the scope and lifetime of objects When an autorelease pool is drained, it calls -release on each object An autorelease pool is created automatically for each iteration of your application s run loop

93 So What s the Catch? What if many objects are autoreleased before the pool pops? Consider the maximum memory footprint of your application

94 A Crowded Pool...

95 Reducing Your High-Water Mark

96 Reducing Your High-Water Mark When many objects will be autoreleased, create and release your own pool

97 Reducing Your High-Water Mark When many objects will be autoreleased, create and release your own pool Usually not necessary, don t do this without thinking!

98 Reducing Your High-Water Mark When many objects will be autoreleased, create and release your own pool Usually not necessary, don t do this without thinking! Tools can help identify cases where it s needed

99 Reducing Your High-Water Mark When many objects will be autoreleased, create and release your own pool Usually not necessary, don t do this without thinking! Tools can help identify cases where it s needed Loops are the classic case

100 Autorelease in a Loop Remember that many methods return autoreleased objects

101 Autorelease in a Loop Remember that many methods return autoreleased objects for (int i = 0; i < somelargenumber; i++) { NSString *string =...; string = [string lowercasestring]; string = [string stringbyappendingstring:...]; NSLog(@ %@, string);

102 Creating an Autorelease Pool One option is to create and release for each iteration

103 Creating an Autorelease Pool One option is to create and release for each iteration for (int i = 0; i < somelargenumber; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *string =...; string = [string lowercasestring]; string = [string stringbyappendingstring:...]; NSLog(@ %@, string); [pool release];

104 Outliving the Autorelease Pool What if some object is needed outside the scope of the pool?

105 Outliving the Autorelease Pool What if some object is needed outside the scope of the pool? NSString *stringtoreturn = nil; for (int i = 0; i < somelargenumber; i++) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSString *string =...; string = [string stringbyappendingstring:...]; if ([string somecondition]) { stringtoreturn = [string retain]; [pool release]; if (stringtoreturn) break; return [stringtoreturn autorelease];

106 Reducing Use of Autorelease Another option is to cut down on use of autoreleased objects Not always possible if you re callling into someone else s code When it makes sense, switch to alloc/init/release In previous example, perhaps use a single NSMutableString?

107 Object Creation Overhead Most of the time, creating and deallocating objects is not a insignificant hit to application performance In a tight loop, though, it can become a problem...

108 Object Creation Overhead Most of the time, creating and deallocating objects is not a insignificant hit to application performance In a tight loop, though, it can become a problem... for (int i = 0; i < somelargenumber; i++) { MyObject *object = [[MyObject alloc] initwithvalue:...]; [object dosomething]; [object release]; 2

109 Reusing Objects

110 Reusing Objects Update existing objects rather than creating new ones

111 Reusing Objects Update existing objects rather than creating new ones Combine intuition and evidence to decide if it s necessary MyObject *myobject = [[MyObject alloc] init]; for (int i = 0; i < somelargenumber; i++) { myobject.value =...; [myobject dosomething]; [myobject release];

112 Reusing Objects Update existing objects rather than creating new ones Combine intuition and evidence to decide if it s necessary MyObject *myobject = [[MyObject alloc] init]; for (int i = 0; i < somelargenumber; i++) { myobject.value =...; [myobject dosomething]; [myobject release]; Remember -[UITableView dequeuereusablecellwithidentifier]

113 Memory Warnings

114 Memory Warnings Coexist with system applications

115 Memory Warnings Coexist with system applications Memory warnings issued when memory runs out

116 Memory Warnings Coexist with system applications Memory warnings issued when memory runs out Respond to memory warnings or face dire consequences!

117 Memory Warnings Coexist with system applications Memory warnings issued when memory runs out Respond to memory warnings or face dire consequences!

118 Memory Warnings Coexist with system applications Memory warnings issued when memory runs out Respond to memory warnings or face dire consequences!

119 Responding to Memory Warnings Every view controller gets -didreceivememorywarning By default, releases the view if it s not visible Release other expensive resources in your subclass

120 Responding to Memory Warnings Every view controller gets -didreceivememorywarning By default, releases the view if it s not visible Release other expensive resources in your subclass - (void)didreceivememorywarning { // Always call super [super didreceivememorywarning]; // Release expensive resources [expensiveresource release]; expensiveresource = nil;

121 Responding to Memory Warnings Every view controller gets -didreceivememorywarning By default, releases the view if it s not visible Release other expensive resources in your subclass - (void)didreceivememorywarning { // Always call super [super didreceivememorywarning]; // Release expensive resources [expensiveresource release]; expensiveresource = nil; App Delegate gets -applicationdidreceivememorywarning:

122 What Other Resources Do I Release? Images Sounds Cached data

123 What Other Resources Do I Release? Images Sounds Cached data

124 Use SQLite/Core Data for Large Data Sets Many data formats keep everything in memory SQLite can work with your data in chunks

125 More on Memory Performance Memory Usage Performance Guidelines Performance/Conceptual/ManagingMemory/

126 Concurrency

127 Why Concurrency? With a single thread, long-running operations may interfere with user interaction Multiple threads allow you to load resources or perform computations without locking up your entire application

128 Threads on the iphone Based on the POSIX threading API /usr/include/pthread.h Higher-level wrappers in the Foundation framework

129 NSThread Basics Run loop automatically instantiated for each thread Each NSThread needs to create its own autorelease pool Convenience methods for messaging between threads

130 Typical NSThread Use Case

131 Typical NSThread Use Case - (void)someaction:(id)sender { // Fire up a new thread [NSThread detachnewthreadselector:@selector(dowork:) withtarget:self object:somedata];

132 Typical NSThread Use Case - (void)someaction:(id)sender { // Fire up a new thread [NSThread detachnewthreadselector:@selector(dowork:) withtarget:self object:somedata]; - (void)dowork:(id)somedata { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; [somedata dolotsofwork]; // Message back to the main thread [self performselectoronmainthread:@selector(alldone:) withobject:[somedata result] waituntildone:no]; [pool release];

133 UIKit and Threads Unless otherwise noted, UIKit classes are not threadsafe Objects must be created and messaged from the main thread You can create a UIImage on a background thread But you can t set it on a UIImageView

134 Locks Protect critical sections of code, mediate access to shared data NSLock and subclasses

135 Locks Protect critical sections of code, mediate access to shared data NSLock and subclasses - (void)init { mylock = [[NSLock alloc] init]; - (void)somemethod { [mylock lock]; // We only want one thread executing this code at once [mylock unlock]

136 Conditions

137 Conditions NSCondition is useful for producer/consumer model

138 Conditions NSCondition is useful for producer/consumer model // On the producer thread - (void)producedata { [condition lock]; // Produce new data newdataexists = YES; [condition signal]; [condition unlock];

139 Conditions NSCondition is useful for producer/consumer model // On the producer thread - (void)producedata { [condition lock]; // Produce new data newdataexists = YES; // On the consumer thread - (void)consumedata { [condition lock]; while(!newdataexists) { [condition wait]; [condition signal]; [condition unlock]; // Consume the new data newdataexists = NO; [condition unlock];

140 Conditions NSCondition is useful for producer/consumer model // On the producer thread - (void)producedata { [condition lock]; // Produce new data newdataexists = YES; // On the consumer thread - (void)consumedata { [condition lock]; while(!newdataexists) { [condition wait]; [condition signal]; [condition unlock]; // Consume the new data newdataexists = NO; [condition unlock]; Wait is equivalent to: unlock, sleep until signalled, lock

141 The Danger of Locks Very difficult to get locking right! All it takes is one poorly behaved client Accessing shared data outside of a lock Deadlocks Priority inversion

142 Threading Pitfalls

143 Threading Pitfalls Subtle, nondeterministic bugs may be introduced

144 Threading Pitfalls Subtle, nondeterministic bugs may be introduced Code may become more difficult to maintain

145 Threading Pitfalls Subtle, nondeterministic bugs may be introduced Code may become more difficult to maintain In the worst case, more threads can mean slower code

146 Alternatives to Threading

147 Alternatives to Threading Asynchronous (nonblocking) functions Specify target/action or delegate for callback NSURLConnection has synchronous and asynchronous variants

148 Alternatives to Threading Asynchronous (nonblocking) functions Specify target/action or delegate for callback NSURLConnection has synchronous and asynchronous variants Timers One-shot or recurring Specify a callback method Managed by the run loop

149 Alternatives to Threading Asynchronous (nonblocking) functions Specify target/action or delegate for callback NSURLConnection has synchronous and asynchronous variants Timers One-shot or recurring Specify a callback method Managed by the run loop Higher level constructs like operations

150 NSOperation Abstract superclass Manages thread creation and lifecycle Encapsulate a unit of work in an object Specify priorities and dependencies

151 Creating an NSOperation Subclass

152 Creating an NSOperation Subclass Define a custom init method - (id)initwithsomeobject:(id)someobject { self = [super init]; if (self) { self.someobject = someobject; return self;

153 Creating an NSOperation Subclass Define a custom init method - (id)initwithsomeobject:(id)someobject { self = [super init]; if (self) { self.someobject = someobject; return self; Override -main method to do work - (void)main { [someobject dolotsoftimeconsumingwork];

154 NSOperationQueue Operations are typically scheduled by adding to a queue Choose a maximum number of concurrent operations Queue runs operations based on priority and dependencies

155 Using an NSInvocationOperation Concrete subclass of NSOperation For lightweight tasks where creating a subclass is overkill

156 Using an NSInvocationOperation Concrete subclass of NSOperation For lightweight tasks where creating a subclass is overkill - (void)someaction:(id)sender { NSInvocationOperation *operation = [[NSInvocationOperation alloc] initwithtarget:self selector:@selector(dowork:) object:someobject]; [queue addobject:operation]; [operation release];

157 More on Concurrent Programming Threading Programming Guide Cocoa/Conceptual/Multithreading

158 Additional Tips & Tricks

159 Drawing Performance Avoid transparency when possible Opaque views are much faster to draw than transparent views Especially important when scrolling Don t call -drawrect: yourself Use -setneedsdisplayinrect: instead of -setneedsdisplay Use CoreAnimation Instrument

160 Reuse Table View Cells UITableView provides mechanism for reusing table view cells

161 Reuse Table View Cells UITableView provides mechanism for reusing table view cells - (UITableViewCell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { return cell;

162 Reuse Table View Cells UITableView provides mechanism for reusing table view cells - (UITableViewCell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { // Ask the table view if it has a cell we can reuse UITableViewCell *cell = [tableview dequeuereusablecellwithidentifier:myidentifier]; return cell;

163 Reuse Table View Cells UITableView provides mechanism for reusing table view cells - (UITableViewCell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { // Ask the table view if it has a cell we can reuse UITableViewCell *cell = [tableview dequeuereusablecellwithidentifier:myidentifier]; if (!cell) { // If not, create one with our identifier cell = [[UITableViewCell alloc] initwithframe:cgrectzero identifier:myidentifier]; [cell autorelease]; return cell;

164 Get notified Don t continuously poll! Unless you must, which is rare Hurts both responsiveness and battery life Look in the documentation for a notification, delegate callback or other asynchronous API

165 Take Samples Instrument that lets you monitor CPU usage Backtrace taken every fraction of a second Higher samples = better candidates for optimization

166 Recap Performance is an art and a science Combine tools & concrete data with intuition & best practices Don t waste memory Concurrency is tricky, abstract it if possible Drawing is expensive, avoid unnecessary work

CS193P - Lecture 10. iphone Application Development. Performance

CS193P - Lecture 10. iphone Application Development. Performance CS193P - Lecture 10 iphone Application Development Performance 1 Announcements 2 Announcements Paparazzi 2 is due next Wednesday at 11:59pm 2 Announcements Paparazzi 2 is due next Wednesday at 11:59pm

More information

Mobile Application Development

Mobile Application Development Object Lifecycle Mobile Application Development Creating objects Memory management Destroying objects Basic ios Development 11-Nov-11 Mobile App Development 1 11/11/11 2 Object Creation Two step process

More information

Announcements. Today s Topics

Announcements. Today s Topics Announcements We will discuss final project ideas on Monday Three guest presenters coming to class Lab 5 is due on Wednesday Nov 4 th 1 Extensible - CSE 436 Software Networking Engineering Platform Workshop

More information

CS193P - Lecture 11. iphone Application Development. Text Input Presenting Content Modally

CS193P - Lecture 11. iphone Application Development. Text Input Presenting Content Modally CS193P - Lecture 11 iphone Application Development Text Input Presenting Content Modally 1 Announcements 2 Announcements Paparazzi 3 assignment is due Wednesday 2/17 2 Announcements Paparazzi 3 assignment

More information

ITP 342 Advanced Mobile App Dev. Memory

ITP 342 Advanced Mobile App Dev. Memory ITP 342 Advanced Mobile App Dev Memory Memory Management Objective-C provides two methods of application memory management. 1. In the method described in this guide, referred to as manual retain-release

More information

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

Design Phase. Create a class Person. Determine the superclass. NSObject (in this case) Design Phase Create a class Person Determine the superclass NSObject (in this case) 8 Design Phase Create a class Person Determine the superclass NSObject (in this case) What properties should it have?

More information

Announcement. Final Project Proposal Presentations and Updates

Announcement. Final Project Proposal Presentations and Updates Announcement Start Final Project Pitches on Wednesday Presentation slides dues by Tuesday at 11:59 PM Email slides to cse438ta@gmail.com Extensible Networking Platform 1 1 - CSE 438 Mobile Application

More information

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

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties CS193P - Lecture 3 iphone Application Development Custom Classes Object Lifecycle Autorelease Properties 1 Announcements Assignments 1A and 1B due Wednesday 1/13 at 11:59 PM Enrolled Stanford students

More information

Announcements. Paparazzi 3 assignment is due Wednesday 2/17 This Friday s extra session will feature Evan Doll

Announcements. Paparazzi 3 assignment is due Wednesday 2/17 This Friday s extra session will feature Evan Doll CS193P - Lecture 11 iphone Application Development Text Input Presenting Content Modally 1 Announcements Paparazzi 3 assignment is due Wednesday 2/17 This Friday s extra session will feature Evan Doll

More information

Mobile Application Development

Mobile Application Development Mobile Application Development Lecture 13 Introduction to ObjectiveC Part II 2013/2014 Parma Università degli Studi di Parma Lecture Summary Object creation Memory management Automatic Reference Counting

More information

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

IPHONE DEVELOPMENT. Getting Started with the iphone SDK IPHONE DEVELOPMENT Getting Started with the iphone SDK OBJECTIVE-C The Big Picture STRICT SUPERSET OF C The Objective C Language Any C stuff applies Standard libs are here (time, sqrt etc) The C Language

More information

Mobile Application Programming. Memory Management

Mobile Application Programming. Memory Management Mobile Application Programming Memory Management Memory Management Ownership Model Memory Management in Objective-C is based on an ownership model. Objects may have many owners. Actions that result in

More information

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management CS193E Lecture #3 Categories and Protocols Cocoa Memory Management Winter 2008, Dempsey/Marcos 1 Today s Topics Questions from Assignment 1A or 1B? Categories Protocols Cocoa Memory Management Object life

More information

Objective-C and COCOA Applications

Objective-C and COCOA Applications Objective-C and COCOA Applications Fall, 2012 Prof. Massimiliano "Max" Pala pala@nyu.edu Overview X-Code IDE Basics Objective-C Classes Methods Invocations Important Types Memory Management Protocols Exceptions

More information

CS 47. Beginning iphone Application Development

CS 47. Beginning iphone Application Development CS 47 Beginning iphone Application Development Introductions Who, why, which? Shameless Plug: LoudTap Wifi Access (If it works..) SSID: Stanford Username/password: csp47guest Expectations This is a programming

More information

Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer

Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer Advanced Memory Analysis with Instruments Daniel Delwood Performance Tools Engineer 2 Memory Analysis What s the issue? Memory is critical to performance Limited resource Especially on iphone OS 3 4 Memory

More information

Memory Management: The Details

Memory Management: The Details Lecture 10 Memory Management: The Details Sizing Up Memory Primitive Data Types Complex Data Types byte: char: short: basic value (8 bits) 1 byte 2 bytes Pointer: platform dependent 4 bytes on 32 bit machine

More information

Collections & Memory Management. Lecture 2

Collections & Memory Management. Lecture 2 Collections & Memory Management Lecture 2 Demo: Accessing Documentation Collections NSArray a list of objects in order [array objectatindex:0] [array objectatindex:3] Counting starts at zero, not one NSSet

More information

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011 Developing Applications for iphone 4, ipod Touch, & ipad Today Dynamic Binding Introspection Foundation Framework Enumeration More Objective-C Allocating and Initializing objects Memory Management Demo

More information

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

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes Review iphone Application Programming Lecture 2: Objective-C, Cocoa Device restrictions Gero Herkenrath Media Computing Group RWTH Aachen University Winter Semester 2013/2014 http://hci.rwth-aachen.de/iphone

More information

the gamedesigninitiative at cornell university Lecture 9 Memory Management

the gamedesigninitiative at cornell university Lecture 9 Memory Management Lecture 9 Gaming Memory Constraints Redux Wii-U Playstation 4 2GB of RAM 1GB dedicated to OS Shared with GPGPU 8GB of RAM Shared GPU, 8-core CPU OS footprint unknown 2 Two Main Concerns with Memory Getting

More information

CS193P - Lecture 8. iphone Application Development. Scroll Views & Table Views

CS193P - Lecture 8. iphone Application Development. Scroll Views & Table Views CS193P - Lecture 8 iphone Application Development Scroll Views & Table Views Announcements Presence 1 due tomorrow (4/28)! Questions? Presence 2 due next Tuesday (5/5) Announcements Enrolled students who

More information

Today s Topics. Scroll views Table views. UITableViewController Table view cells. Displaying data Controlling appearance & behavior

Today s Topics. Scroll views Table views. UITableViewController Table view cells. Displaying data Controlling appearance & behavior Today s Topics Scroll views Table views Displaying data Controlling appearance & behavior UITableViewController Table view cells Scroll Views UIScrollView For displaying more content than can fit on the

More information

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

Objective-C ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University. 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

More information

epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE

epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE + = Prototype iphone ipad Why iphone apps Simplicity Control Speed Revenue Epicurious Defined as a Recipe Utility Cookbook

More information

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010 Developing Applications for iphone 4, ipod Touch, & ipad Today More Core Data What does the code for the custom NSManagedObject subclasses generated by Xcode look like? Querying for (fetching) objects

More information

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010 Data IAP 2010 iphonedev.csail.mit.edu edward benson / eob@csail.mit.edu Today Property Lists User Defaults Settings Panels CoreData Property Lists Today Add persistence. plist 1. Using Property Lists in

More information

Assignment II: Foundation Calculator

Assignment II: Foundation Calculator Assignment II: Foundation Calculator Objective The goal of this assignment is to extend the CalculatorBrain from last week to allow inputting variables into the expression the user is typing into the calculator.

More information

Mobile Application Programming. Objective-C Classes

Mobile Application Programming. Objective-C Classes Mobile Application Programming Objective-C Classes Custom Classes @interface Car : NSObject #import Car.h + (int) viper; - (id) initwithmodel:(int)m; @implementation Car Point position; float velocity;

More information

Apple Development Technology Workshops

Apple Development Technology Workshops Apple Development Technology Workshops Workshop 10 Table Views Building iphone Apps. Pt 2 Fall 2008 Hafez Rouzati Fall 2008 Zach Pousman Last Week UIViewControllers Organizing Content & Building iphone

More information

Grand Central Dispatch

Grand Central Dispatch A better way to do multicore. (GCD) is a revolutionary approach to multicore computing. Woven throughout the fabric of Mac OS X version 10.6 Snow Leopard, GCD combines an easy-to-use programming model

More information

ITP 342 Mobile App Dev. Table Views

ITP 342 Mobile App Dev. Table Views ITP 342 Mobile App Dev Table Views Table Views The most common mechanism used to display lists of data to the user Highly configurable objects that can be made to look practically any way you want them

More information

Designing iphone Applications

Designing iphone Applications Designing iphone Applications 4 Two Flavors of Mail 5 Organizing Content 6 Organizing Content 6 Organizing Content 6 Organizing Content 6 Organizing Content Focus on your user s data 6 Organizing Content

More information

Concurrency. CS 442: Mobile App Development Michael Saelee

Concurrency. CS 442: Mobile App Development Michael Saelee Concurrency CS 442: Mobile App Development Michael Saelee note: ios devices are now (mostly) multi-core; i.e., concurrency may allow for real performance gains! but the more common incentive

More information

Review (Basic Objective-C)

Review (Basic Objective-C) Classes Header.h (public) versus Implementation.m (private) @interface MyClass : MySuperclass... @end (only in header file) @interface MyClass()... @end (only in implementation file) @implementation...

More information

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

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011 Developing Applications for ios Today Core Data Thread Safety NSManagedObjectContext is not thread-safe. What to do about that. Core Data and Table View Very common way to view data from a Core Data database

More information

Memory management COSC346

Memory management COSC346 Memory management COSC346 Life cycle of an object Create a reference pointer Allocate memory for the object Initialise internal data Do stuff Destroy the object Release memory 2 Constructors and destructors

More information

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

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes Review iphone Application Programming Lecture 2: Objective-C, Cocoa Device restrictions Gero Herkenrath Media Computing Group RWTH Aachen University Winter Semester 2013/2014 http://hci.rwth-aachen.de/iphone

More information

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007 CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes

More information

Data Management

Data Management Core Data Utility Tutorial Data Management 2010-09-19 Apple Inc. 2005, 2010 Apple Inc. All rights reserved. exclusion may not apply to you. This warranty gives you specific legal rights, and you may also

More information

CS193p Spring 2010 Thursday, April 29, 2010

CS193p Spring 2010 Thursday, April 29, 2010 CS193p Spring 2010 Announcements You should have received an e-mail by now If you received e-mail approving enrollment, but are not in Axess, do it! If you have any questions, please ask via e-mail or

More information

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

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net OVERVIEW Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net Microsoft MVP for 4 years C#, WinForms, WPF, Silverlight Joined Cynergy about

More information

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

Objective-C Part 2 (ECS189H) Ken Joy Serban Porumbescu Objective-C Part 2 (ECS189H) Ken Joy joy@cs.ucdavis.edu Serban Porumbescu porumbes@cs.ucdavis.edu Today Objective-C Memory Management Properties Categories and Protocols Delegates Objective-C Memory Management

More information

CS 160: Interactive Programming

CS 160: Interactive Programming CS 160: Interactive Programming Professor John Canny 3/8/2006 1 Outline Callbacks and Delegates Multi-threaded programming Model-view controller 3/8/2006 2 Callbacks Your code Myclass data method1 method2

More information

Naviga&on and Tab Bar Controllers and Table View

Naviga&on and Tab Bar Controllers and Table View Naviga&on and Tab Bar Controllers and Table View UINaviga)onController Stack of view controllers Naviga)on bar How It Fits Together Top view controller s view Top view controller s )tle Previous view controller

More information

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

COMP327 Mobile Computing Session: Tutorial Objective-C and the Foundation Framework COMP327 Mobile Computing Session: 2010-2011 Tutorial 4-5 - Objective-C and the Foundation Framework 1 In these Tutorial Slides... These slides introduce you to Objective-C, with a focus on the object-oriented

More information

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.

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. Deck.h #import @interface Deck : NSObject @interface Deck() @implementation Deck Deck.m Let s look at another class. This one represents a deck of cards. Deck.h #import

More information

Synchronization SPL/2010 SPL/20 1

Synchronization SPL/2010 SPL/20 1 Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization

More information

Performance

Performance Threading Programming Guide Performance 2010-04-28 Apple Inc. 2010 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form

More information

When we re first learning Cocoa (or Java, or Qt, or any other application framework),

When we re first learning Cocoa (or Java, or Qt, or any other application framework), MacDevCenter http://www.macdevcenter.com/lpt/a/4752 6 April 2004 The Cocoa Controller Layer by Michael Beam When we re first learning Cocoa (or Java, or Qt, or any other application framework), one of

More information

CMSC 330: Organization of Programming Languages

CMSC 330: Organization of Programming Languages CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple

More information

Garbage Collection. CS 351: Systems Programming Michael Saelee

Garbage Collection. CS 351: Systems Programming Michael Saelee Garbage Collection CS 351: Systems Programming Michael Saelee = automatic deallocation i.e., malloc, but no free! system must track status of allocated blocks free (and potentially reuse)

More information

Advanced Object- C Features

Advanced Object- C Features Advanced Object- C Features Advanced Features Proper6es Categories Protocols Delegates Selectors Key- Value Coding Predicators Proper6es Provide access to object a?ributes Shortcut to implemen6ng ge?er/se?er

More information

Threads Chapter 5 1 Chapter 5

Threads Chapter 5 1 Chapter 5 Threads Chapter 5 1 Chapter 5 Process Characteristics Concept of Process has two facets. A Process is: A Unit of resource ownership: a virtual address space for the process image control of some resources

More information

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015

Grand Central Dispatch and NSOperation. CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015 Grand Central Dispatch and NSOperation CSCI 5828: Foundations of Software Engineering Lecture 28 12/03/2015 1 Credit Where Credit Is Due Most of the examples in this lecture were inspired by example code

More information

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

Intro to Native ios Development. Dave Koziol Arbormoon Software, Inc. Intro to Native ios Development Dave Koziol Arbormoon Software, Inc. About Me Long time Apple Developer (20 WWDCs) Organizer Ann Arbor CocoaHeads President & ios Developer at Arbormoon Software Inc. Wunder

More information

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University G22.2110-001 Programming Languages Spring 2010 Lecture 13 Robert Grimm, New York University 1 Review Last week Exceptions 2 Outline Concurrency Discussion of Final Sources for today s lecture: PLP, 12

More information

Multithreading and Interactive Programs

Multithreading and Interactive Programs Multithreading and Interactive Programs CS160: User Interfaces John Canny. Last time Model-View-Controller Break up a component into Model of the data supporting the App View determining the look of the

More information

Threads. CS3026 Operating Systems Lecture 06

Threads. CS3026 Operating Systems Lecture 06 Threads CS3026 Operating Systems Lecture 06 Multithreading Multithreading is the ability of an operating system to support multiple threads of execution within a single process Processes have at least

More information

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

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall Stanford Developing Applications for ios Today Drag and Drop Transferring information around within and between apps. EmojiArt Demo Drag and drop an image to get our EmojiArt masterpieces started. UITableView

More information

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science

Multithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the

More information

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control.

What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope. C Flow Control. C Flow Control David Chisnall February 1, 2011 Outline What the CPU Sees Basic Flow Control Conditional Flow Control Structured Flow Control Functions and Scope Disclaimer! These slides contain a lot of

More information

ITP 342 Mobile App Dev. Table Views

ITP 342 Mobile App Dev. Table Views ITP 342 Mobile App Dev Table Views Tables A table presents data as a scrolling, singlecolumn list of rows that can be divided into sections or groups. Use a table to display large or small amounts of information

More information

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding

CS193E Lecture 7. Document-based Applications NSTableView Key-Value Coding CS193E Lecture 7 Document-based Applications NSTableView Key-Value Coding Agenda Questions? Review: delegates, MVC Document-based apps Table views Key Value Coding Model, View, Controller Controller Model

More information

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable)

CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) CSL373: Lecture 5 Deadlocks (no process runnable) + Scheduling (> 1 process runnable) Past & Present Have looked at two constraints: Mutual exclusion constraint between two events is a requirement that

More information

ios Mobile Development

ios Mobile Development ios Mobile Development Today UITableView! Data source-driven vertical list of views.! ipad! Device-specific UI idioms.! Demo! Shutterbug UITableView Very important class for displaying data in a table!

More information

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

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

ios Development Lecture 1 Introduction to Objective-C Ing. Simone Cirani ios Development Lecture 1 Introduction to ObjectiveC Ing. Simone Cirani email: simone.cirani@unipr.it http://www.tlc.unipr.it/cirani Simone Cirani, Ph.D. Corso IFTS Cisita ios Development 2014 Parma Università

More information

Java s Implementation of Concurrency, and how to use it in our applications.

Java s Implementation of Concurrency, and how to use it in our applications. Java s Implementation of Concurrency, and how to use it in our applications. 1 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video

More information

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class

More information

Introductory ios Development

Introductory ios Development Introductory ios Development 152-164 Unit 5 - Multi-View Apps Quick Links & Text References What is a Delegate? What is a Protocol? Delegates, Protocols and TableViews Creating a Master-Detail App Modifying

More information

Monday, 1 November The ios System

Monday, 1 November The ios System The ios System System Overview System Overview System Overview System Overview System Overview System Overview Foundation Classes (Useful) Foundation Framework Value and collection classes User defaults

More information

Reference Counting. Steven R. Bagley

Reference Counting. Steven R. Bagley Reference Counting Steven R. Bagley Previously Objects are blocks of memory Store pointer to base of object s memory so we can reference it Memory needs to be released when the object is no longer needed

More information

Structure of Programming Languages Lecture 10

Structure of Programming Languages Lecture 10 Structure of Programming Languages Lecture 10 CS 6636 4536 Spring 2017 CS 6636 4536 Lecture 10: Classes... 1/23 Spring 2017 1 / 23 Outline 1 1. Types Type Coercion and Conversion Type Classes, Generics,

More information

Principles of Programming Languages. Objective-C. Joris Kluivers

Principles of Programming Languages. Objective-C. Joris Kluivers Principles of Programming Languages Objective-C Joris Kluivers joris.kluivers@gmail.com History... 3 NeXT... 3 Language Syntax... 4 Defining a new class... 4 Object identifiers... 5 Sending messages...

More information

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts ISBN 0-321-49362-1 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language

More information

ECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017

ECE 550D Fundamentals of Computer Systems and Engineering. Fall 2017 ECE 550D Fundamentals of Computer Systems and Engineering Fall 2017 The Operating System (OS) Prof. John Board Duke University Slides are derived from work by Profs. Tyler Bletsch and Andrew Hilton (Duke)

More information

CS 241 Honors Memory

CS 241 Honors Memory CS 241 Honors Memory Ben Kurtovic Atul Sandur Bhuvan Venkatesh Brian Zhou Kevin Hong University of Illinois Urbana Champaign February 20, 2018 CS 241 Course Staff (UIUC) Memory February 20, 2018 1 / 35

More information

Concurrency, Thread. Dongkun Shin, SKKU

Concurrency, Thread. Dongkun Shin, SKKU Concurrency, Thread 1 Thread Classic view a single point of execution within a program a single PC where instructions are being fetched from and executed), Multi-threaded program Has more than one point

More information

Mobile Application Development

Mobile Application Development Mobile Application Development Lecture 12 Introduction to ObjectiveC 2013/2014 Parma Università degli Studi di Parma Lecture Summary ObjectiveC language basics Classes and objects Methods Instance variables

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CS193k, Stanford Handout #10. HW2b ThreadBank

CS193k, Stanford Handout #10. HW2b ThreadBank CS193k, Stanford Handout #10 Spring, 99-00 Nick Parlante HW2b ThreadBank I handed out 2a last week for people who wanted to get started early. This handout describes part (b) which is harder than part

More information

Extensions to Barrelfish Asynchronous C

Extensions to Barrelfish Asynchronous C Extensions to Barrelfish Asynchronous C Michael Quigley michaelforrquigley@gmail.com School of Computing, University of Utah October 27, 2016 1 Abstract The intent of the Microsoft Barrelfish Asynchronous

More information

The Proxy Pattern. Design Patterns In Java Bob Tarr

The Proxy Pattern. Design Patterns In Java Bob Tarr The Proxy Pattern Intent Provide a surrogate or placeholder for another object to control access to it Also Known As Surrogate Motivation A proxy is a person authorized to act for another person an agent

More information

ITP 342 Mobile App Dev

ITP 342 Mobile App Dev ITP 342 Mobile App Dev Grand Central Dispatch Background Processing Grand Central Dispatch (GCD) New API for splitting up the work your app needs to do into smaller chunks that can be spread across multiple

More information

ios: Objective-C Primer

ios: Objective-C Primer ios: Objective-C Primer Jp LaFond Jp.LaFond+e76@gmail.com TF, CS76 Announcements n-puzzle feedback this week (if not already returned) ios Setup project released Android Student Choice project due Tonight

More information

Objective-C Primer. iphone Programmer s Association. Lorenzo Swank September 10, 2008

Objective-C Primer. iphone Programmer s Association. Lorenzo Swank September 10, 2008 Objective-C Primer iphone Programmer s Association Lorenzo Swank September 10, 2008 Disclaimer Content was blatantly and unapologetically stolen from the WWDC 2007 Fundamentals of Cocoa session, as well

More information

Safety SPL/2010 SPL/20 1

Safety SPL/2010 SPL/20 1 Safety 1 system designing for concurrent execution environments system: collection of objects and their interactions system properties: Safety - nothing bad ever happens Liveness - anything ever happens

More information

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 Process creation in UNIX All processes have a unique process id getpid(),

More information

ITP 342 Mobile App Dev. Fundamentals

ITP 342 Mobile App Dev. Fundamentals ITP 342 Mobile App Dev Fundamentals Objective-C Classes Encapsulate data with the methods that operate on that data An object is a runtime instance of a class Contains its own in-memory copy of the instance

More information

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5 iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5 Questions? Announcements Assignment #1 due this evening by 11:59pm Remember, if you wish to use a free late you must email me before

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012

Stanford CS193p. Developing Applications for ios. Spring Stanford CS193p. Spring 2012 Developing Applications for ios Today Blocks Objective-C language feature for in-lining blocks of code Foundation of multi-threaded support (GCD) What is a block? A block of code (i.e. a sequence of statements

More information

CS 326: Operating Systems. Process Execution. Lecture 5

CS 326: Operating Systems. Process Execution. Lecture 5 CS 326: Operating Systems Process Execution Lecture 5 Today s Schedule Process Creation Threads Limited Direct Execution Basic Scheduling 2/5/18 CS 326: Operating Systems 2 Today s Schedule Process Creation

More information

Advanced Programming & C++ Language

Advanced Programming & C++ Language Advanced Programming & C++ Language ~6~ Introduction to Memory Management Ariel University 2018 Dr. Miri (Kopel) Ben-Nissan Stack & Heap 2 The memory a program uses is typically divided into four different

More information

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014

Learning from Bad Examples. CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 Learning from Bad Examples CSCI 5828: Foundations of Software Engineering Lecture 25 11/18/2014 1 Goals Demonstrate techniques to design for shared mutability Build on an example where multiple threads

More information

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

Stanford CS193p. Developing Applications for ios Fall Stanford CS193p. Fall 2013 Developing Applications for ios -14 Today What is this class all about? Description Prerequisites Homework / Final Project ios Overview What s in ios? MVC Object-Oriented Design Concept Objective C (Time

More information

Internal Server Architectures

Internal Server Architectures Chapter3 Page 29 Friday, January 26, 2001 2:41 PM Chapter CHAPTER 3 Internal Server Architectures Often, it is important to understand how software works internally in order to fully understand why it

More information

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive

More information

Processes and Threads. Processes and Threads. Processes (2) Processes (1)

Processes and Threads. Processes and Threads. Processes (2) Processes (1) Processes and Threads (Topic 2-1) 2 홍성수 Processes and Threads Question: What is a process and why is it useful? Why? With many things happening at once in a system, need some way of separating them all

More information