The NetworkManager singleton class handles network requests for the application. It starts monitoring network reachability when initialized. It kicks off the initial data fetch by queuing a request for a specific URL path. The NetworkManager will inform the user of network status and reject requests if offline.
You're on another typical JavaEE-based project, and you find yourself writing the same old infrastructure code. Are you wondering if there's a quicker way to incorporate the basics such as configuration, logging, and email into your application? If so, then this presentation is for you. By using a number of Apache utilities from
Commons, Logging, and other areas, you can learn how to stop re-inventing the wheel.
We'll start with a simple Struts 2 application and iteratively add the ability to:
• Use Commons Lang for String and Date utilities.
• Use Commons Property Configuration to setup and use application Properties.
• Use Commons Logging and Log4J to log messages.
• Generate Excel spreadsheets with POI.
• Use Velocity Templates and Commons Email to format and send email messages.
• Use HttpClient to invoke web apps with HTTP/S.
• Use Commons IOUtils to simplify accessing web content.
'Development using iOS5 NewStuff' keynote for #IDOC2012. Bandung, 18th February 2012.
- iCloud Storage
- CoreImage
- NewsStand
Demo and sample code : https://github.com/DeenNa
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
This intermediate-level talk will teach you techniques using the popular NoSQL database MongoDB and the Python library Ming to write maintainable, high-performance, and scalable applications. We will cover everything you need to become an effective Ming/MongoDB developer from basic PyMongo queries to high-level object-document mapping setups in Ming.
Mobile devices are so useful because they can get on the net with their built-in wi-fi or cellular data radios. But how does this work? In iOS, we have a slew of networking APIs, each appropriate in different situations. From decades-old BSD sockets to the new-in-iOS-5 iCloud, there are a wide range of networking calls available to your app, and an equally wide range of semantics in how to use them. In this talk, we'll start with high-level abstractions like iCloud and other objects that can either load from or save to a URL, then progress down through the stack, grabbing arbitrary content from URLs, self-networking with Bonjour and Game Kit, and finally accessing the socket layer with CFNetwork and BSD sockets.
iCloud sample code at: http://dl.dropbox.com/u/12216224/conferences/codemash12/bonjour-icloud/CloudNotes.zip
Developing application for Windows Phone 7 in TDDMichele Capra
A real example of how to develop an application for Windows Phone 7 with Test Driven Development approach. In this presentation you'll see also hoew to implements the Model-View-ViewModel (MVVM) pattern.
RubyMotion is great for quickly prototyping apps but it lacks the data modelling tools that Xcode provides. Luckily, using Core Data with RubyMotion can actually be easier and quicker with a little help from some 3rd party libraries.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
You're on another typical JavaEE-based project, and you find yourself writing the same old infrastructure code. Are you wondering if there's a quicker way to incorporate the basics such as configuration, logging, and email into your application? If so, then this presentation is for you. By using a number of Apache utilities from
Commons, Logging, and other areas, you can learn how to stop re-inventing the wheel.
We'll start with a simple Struts 2 application and iteratively add the ability to:
• Use Commons Lang for String and Date utilities.
• Use Commons Property Configuration to setup and use application Properties.
• Use Commons Logging and Log4J to log messages.
• Generate Excel spreadsheets with POI.
• Use Velocity Templates and Commons Email to format and send email messages.
• Use HttpClient to invoke web apps with HTTP/S.
• Use Commons IOUtils to simplify accessing web content.
'Development using iOS5 NewStuff' keynote for #IDOC2012. Bandung, 18th February 2012.
- iCloud Storage
- CoreImage
- NewsStand
Demo and sample code : https://github.com/DeenNa
Rapid and Scalable Development with MongoDB, PyMongo, and MingRick Copeland
This intermediate-level talk will teach you techniques using the popular NoSQL database MongoDB and the Python library Ming to write maintainable, high-performance, and scalable applications. We will cover everything you need to become an effective Ming/MongoDB developer from basic PyMongo queries to high-level object-document mapping setups in Ming.
Mobile devices are so useful because they can get on the net with their built-in wi-fi or cellular data radios. But how does this work? In iOS, we have a slew of networking APIs, each appropriate in different situations. From decades-old BSD sockets to the new-in-iOS-5 iCloud, there are a wide range of networking calls available to your app, and an equally wide range of semantics in how to use them. In this talk, we'll start with high-level abstractions like iCloud and other objects that can either load from or save to a URL, then progress down through the stack, grabbing arbitrary content from URLs, self-networking with Bonjour and Game Kit, and finally accessing the socket layer with CFNetwork and BSD sockets.
iCloud sample code at: http://dl.dropbox.com/u/12216224/conferences/codemash12/bonjour-icloud/CloudNotes.zip
Developing application for Windows Phone 7 in TDDMichele Capra
A real example of how to develop an application for Windows Phone 7 with Test Driven Development approach. In this presentation you'll see also hoew to implements the Model-View-ViewModel (MVVM) pattern.
RubyMotion is great for quickly prototyping apps but it lacks the data modelling tools that Xcode provides. Luckily, using Core Data with RubyMotion can actually be easier and quicker with a little help from some 3rd party libraries.
Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.
/*!
* Modernizr v2.0.6
* http://www.modernizr.com
*
* Copyright (c) 2009-2011 Faruk Ates, Paul Irish, Alex Sexton
* Dual-licensed under the BSD or MIT licenses: www.modernizr.com/license/
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton,
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.0.6',
Modernizr = {},
// option for enabling the HTML classes to be added
enableClasses = true,
docElement = document.documentElement,
docHead = document.head || document.getElementsByTagName('head')[0],
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem = document.createElement('input'),
smile = ':)',
toString = Object.prototype.toString,
// List of property values to set for css tests. See ticket #21
prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
// Following spec is to expose vendor-specific style properties as:
// elem.style.WebkitBorderRadius
// and the following would be incorrect:
// elem.style.webkitBorderRadius
// Webkit ghosts their properties in lowercase but Opera & Moz do not.
// Microsoft foregoes prefixes entirely elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
// when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
// with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
// http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
style = ['', ''].join('');
div.id = mod;
div.innerHTML += style;
docElement.appendChild(div);
ret = callback(div, rule);
div.parentNode.removeChild(div);
return !!ret;
},
// adapted from matchMedia polyfill
// by Scott Jehl and Paul Irish
// gist.github.com/786768
testMediaQuery = function( mq ) {
if ( window.matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', funct ...
Core Data with multiple managed object contextsMatthew Morey
When using Core Data for persisting app data multiple managed object contexts (MOC) are often required to avoid blocking UI. Typically you would create a background MOC and listen for changes on the main MOC, merging changes as necessary. With iOS 5, MOCs now have parent context and the ability to set concurrency types. These new features greatly simplify dealing with Core Data on background queues. During this presentation Matt will cover the pros and cons of this new method of dealing with Core Data.
Slides for the 1st lecture on mobile development (dedicated to iOS) at the Faculty of Mathematics and Physics at the Charles University in Prague.
Course page: http://www.inmite.eu/en/talks/mff-2012
Synchronizing without internet - Multipeer Connectivity (iOS)Jorge Maroto
Slides of my presentation in Codemotion 2014, Madrid talking about Multipeer connectivity and how to sync data between devices without need an internet connection or without to create an infraestructure network.
See materials in https://github.com/patoroco/Codemotion-2014-Multipeer-Connectivity
Managing Memory in Swift (Yes, that's a thing)Carl Brown
My talk from Swift Cloud Workshop 2 in Austin, TX on 2017-09-30 about the current state of memory management with Swift in the Cloud, and whether or not Swift on the Server is mature enough for your use-case.
Better Swift from the Foundation up #tryswiftnyc17 09-06Carl Brown
Highlights of some useful Swift coding patterns and ways to avoid common sources of bugs and performance issues. These lessons learned are based on examination of Swift CoreLibs Foundation and other Open Source Swift libraries and projects, as he has contributed to helping bring Swift to the Server.
Current state of tools for developing Swift code on Linux (or on the Mac but with Xcode).
Presented to SwiftAustin on April 5th, 2017 https://www.meetup.com/SwiftAustin/events/238281895/
Inaugural Meetup for the Swift Austin group. Introduction and how-to presentation on getting the latest (or recent) version of Swift running in a Docker or Vagrant VM under MacOS or Windows.
Swift 2.2 Design Patterns CocoaConf Austin 2016Carl Brown
Talk on Swift 2.2, adapting Cocoa/Objective-C Design Patterns to Swift, Design Patterns from other Languages that Swift has adopted, and Swift features that lend themselves to new Design Patterns.
Advanced, Composable Collection Views, From CocoaCoders meetup Austin Feb 12,...Carl Brown
Building complicated data-driven user interfaces can be difficult. Tables are one thing, but what do you do if you need to combine different types of data (with different layout needs) on the same screen?
This week we're going to discuss how to do with, using some Apple-provided sample code from WWDC 2014 as our starting point.
Writing Apps that Can See: Getting Data from CoreImage to Computer Vision - ...Carl Brown
Apps that Can See: Getting Data from CoreImage to Computer
Vision
You hear about the app that can solve a Rubik's Cube after you take pictures of
each side? How about the one that can import Sudoku puzzles by letting you take a
picture of a puzzle? Wouldn't it be cool if your apps could get information that way?
Come and learn how to integrate image processing in your apps. We'll start with
Apple's built-in CoreImage libraries, and then move on to open-source C++ libraries
that let you detect colors, shapes, letters and numbers. We'll go through quite a bit of
sample code that you can take with you to use in your apps.
We'll also talk about practical tips and experiences, like how to debug and
troubleshoot code when things aren't working the way you expected.
360iDev Presentation this year:
As a contract iOS programmer, I spend about 80% of my time working with other people's iOS code - either working as a part of existing teams or taking over incomplete projects from developers who are no longer around. Along the way, I've gathered a list of the common mistakes I've seen people make, the open-source libraries I've seen people misuse the most, and the really simple code changes that can make huge differences in the reliability and performance of your apps. For each mistake or anti-pattern, I'll have an explanation of the issue with it, and at least one potential remedy or remediation that could be taken.
This talk will have a lot of specific code examples on a number of different topics and technologies, so hopefully everyone will learn something. And hopefully at least something will save you some time.
Note that this will be a very opinionated talk, and I'm quite likely to step on someone's pet pattern, so there may be fireworks.
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
In this presentation, we examine the challenges and limitations of relying too heavily on PHP frameworks in web development. We discuss the history of PHP and its frameworks to understand how this dependence has evolved. The focus will be on providing concrete tips and strategies to reduce reliance on these frameworks, based on real-world examples and practical considerations. The goal is to equip developers with the skills and knowledge to create more flexible and future-proof web applications. We'll explore the importance of maintaining autonomy in a rapidly changing tech landscape and how to make informed decisions in PHP development.
This talk is aimed at encouraging a more independent approach to using PHP frameworks, moving towards a more flexible and future-proof approach to PHP development.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
REST/JSON/CoreData Example Code - A Tour
1. REST/JSON/CoreData
Example Code
github.com/carlbrown/
SeismicJSON
Carl Brown
Twitter: @CarlBrwn
Email: CarlB@PDAgent.com
1
Turn on Camera and ScreenFlow!!
2. Asynchronous iOS Programming Rules
• Threads are bad
• Use Queues instead
• Apple's Concurrency Programming Guide*:
• Page 10: "The Move Away from Threads"
• Page 74: "Migrating Away from Threads"
• Page 74: "Replacing Threads with Dispatch Queues"
* http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html
2
4. UI tasks Must be on the Main
Thread
Often called the "UI" thread for that reason
4
5. CoreData Contexts and Objects are tied to a
thread
• Never share a CoreData object between threads
• Never share a CoreData object between contexts
• Pass objects only by ID and fetch them again
• Always notify other contexts when you've made changes
5
6. Don't cross the threads
•Use the same serial queue to stay on the
same thread
•Use dispatch_get_main_queue() or
[NSOperationQueue mainQueue] to get to the
Main Thread.
6
7. SeismicJSON
The only project we'll be
working with today
Feel free to run it and play
with it for a couple of minutes
Also on github so you can
see how it was written.
7
8. First Exercise:
Follow the Code
8
This is a vital skill to have. We don't expect people to
write in English without reading a lot of English first, but
programmers consistently spend more time writing code
than reading it while learning a new language.
9. Please Open
MasterView
Controller.m
This is pretty much a
tableViewController like
you've seen before.
Ignore the #if conditionals
this run-through
9
Ignore the #if conditionals this run-through
10. MasterViewController
should be mostly familiar
• Cell labels filled in from Model Object
• custom XIB for TableViewCell
• dateFormatter in viewDidLoad
• segmentedController sets FRC sorting
• actionSheet for adding rows (you can figure out)
• some iPad stuff (not Rocket Science)
• #if conditional stuff (for later)
10
27. -(void) imageDidBecomeAvailableAtPath:(NSString *) path {
if (![[path lastPathComponent]
isEqualToString:self.imageFileName]) {
NSLog(@"Warning: notified of incorrect file:
%@, should have been %@",[path
lastPathComponent],self.imageFileName);
//try again
[self setImageFileName:self.imageFileName];
return;
}
Only load the file we're expecting (race condition checking)
imageDidBecomeAvailableAtPath
1/2
27
28. //load image off the main queue
UIImage *imageToLoad=[UIImage imageWithContentsOfFile:path];
dispatch_async(dispatch_get_main_queue(), ^{
[self setImage:imageToLoad];
[self setNeedsDisplay];
});
}
Set our image with the file now on disk
imageDidBecomeAvailableAtPath
2/2
28
29. Summary of ActivityIndicatingImageView
• Start the view with a spinner telling the user we are working on
something
• See if the file is already on disk, and use it if so.
• If not, we ask the Network Manager to get the file for us
• The Network Manager creates an operation to get our file
(presumably from the network) and write it to disk
• The Network Manager tells us the file is ready
• We load the file into our image property
• Now that we have an image, the spinner hides
29
30. Recommended
Networking Strategy
•Always* load the UI from local storage
•Core Data or local file or something
•Always* put network data in local storage
•Then tell the UI to refresh itself
•Put up a placeholder if no data
*Except with live web pages or HTTP streaming
30
Some people argue with me about this, but it's served me well for years
31. Why do it that way?
•Separates network code from UI code
•Easier to test
•Much faster response if previous data
•Much better user experience offline
31
32. Why wouldn't you?
•Pointless if the network is infinitely fast
and infinitely reliable*
•More effort than "Unbreakable Glass"
loading screens
*c.f. http://en.wikipedia.org/wiki/Fallacies_of_Distributed_Computing
32
34. NSOperation
• Been around since the first iPhone OS SDK
• Way to encapsulate the pieces of a task in one
place
• Can be queried, suspended or canceled
• Simple selector call or block variants
• NSOperations are placed in NSOperationQueues
34
35. NSOperationQueue
• Long-lived (presumably) queue that can contain
numerous operations
• Can be serial or concurrent
• Can be suspended or canceled
• Nice (but verbose) Objective-C syntax
• Will stay on the same thread, if serial
• [NSOperationQueue mainQueue] is always on the Main
Thread
35
36. Dispatch Queues
•C-style (concise) syntax
•quicker to use in-place
•much less typing than declaring an
NSOperation and adding to Queue
•Harder to manage or cancel
36
37. Which to use?
• No hard-and-fast rules, but...
• I tend to use NSOperations for:
• things I'm going to do several times
• things that have non-trivial complexity
• I tend to use dispatch_async() for things:
• with less than 10 or so lines of code
• done only once in the App
• that won't need to change when spec changes
37
38. Waiting in Cocoa
•Don't Sleep
•Don't use locks
•Yield to the RunLoop
•See the FetchOperation for example
•Sleeping or Locking Freezes the Thread
38
39. Be Nice to Threads
• POSIX Threads are a finite resource
• The system will spin up more if tasks are
waiting
• But when no more can start, things will hang
• See: WWDC2012 Session Session 712 -
Asynchronous Design Patterns with Blocks,
GCD, and XPC
39
42. //Make this a 1 to show notifications, and a 0 to show parent contexts
#define kUSE_NSNOTIFICATIONS_FOR_CONTEXT_MERGE 0
//if using notifications, set this to 1 to have them in the App
Delegate
#define kNSNOTIFICATIONS_HANDLED_IN_APPDELEGATE 0
Note: I'm not usually a fan of this kind of conditional
compilation, but for this case, I thought it would
let you play with project in the debugger in a
cleaner way than with traditional if's.
Project Variations
42
52. applicationDidBecomeActive:
(UIApplication *)application
• Happens when App becomes full-focus
• After launch
• Or after returning from dealing with alert
• Or after dealing with "most recently used
apps" along bottom of screen
• Here I'm adding a notification observer
52
55. - (void)changesSaved:(NSNotification *)notification {
if (![NSThread isMainThread]) {
dispatch_async(dispatch_get_main_queue(), ^{
[self changesSaved:notification];
});
return;
}
if ([notification object] != self.managedObjectContext) {
[self.managedObjectContext
mergeChangesFromContextDidSaveNotification:notification];
}
}
If not on Main, go there
55
78. -(void) finish {
[self setDone:YES];
if (self.delegate) {
[self.delegate decrementActiveFetches];
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
Inform user we're done
78
79. -(void) finish {
[self setDone:YES];
if (self.delegate) {
[self.delegate decrementActiveFetches];
}
CFRunLoopStop(CFRunLoopGetCurrent());
}
Stop the runloop & get
off
79
80. Other methods there
• didReceiveResponse
• remember response
• truncate data
• (can get more than one response)
• didReceiveData
• append data
• didFailWithError
• report error to our delegate
80
87. id objectFromJSON = [NSJSONSerialization
JSONObjectWithData:self.fetchedData options:0 error:&error];
if (objectFromJSON) {
#if kUSE_NSNOTIFICATIONS_FOR_CONTEXT_MERGE
NSManagedObjectContext *context =
[[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:
self.mainContext.persistentStoreCoordinator];
#else
NSManagedObjectContext *context = [[NSManagedObjectContext
alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[context setParentContext:[self mainContext]];
#endif
If the JSON was good
87
88. id objectFromJSON = [NSJSONSerialization
JSONObjectWithData:self.fetchedData options:0 error:&error];
if (objectFromJSON) {
#if kUSE_NSNOTIFICATIONS_FOR_CONTEXT_MERGE
NSManagedObjectContext *context =
[[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:
self.mainContext.persistentStoreCoordinator];
#else
NSManagedObjectContext *context = [[NSManagedObjectContext
alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
[context setParentContext:[self mainContext]];
#endif
Make new
ManagedObjectContext
88
89. NSDictionary *jsonDict = (NSDictionary *) objectFromJSON;
if (jsonDict) {
NSArray *events = [jsonDict objectForKey:@"features"];
if (events) {
for (NSDictionary *eventDict in events) {
connectionDidFinish
Loading 3/n
89
90. NSDictionary *jsonDict = (NSDictionary *) objectFromJSON;
if (jsonDict) {
NSArray *events = [jsonDict objectForKey:@"features"];
if (events) {
for (NSDictionary *eventDict in events) {
If we got a dictionary
90
91. NSDictionary *jsonDict = (NSDictionary *) objectFromJSON;
if (jsonDict) {
NSArray *events = [jsonDict objectForKey:@"features"];
if (events) {
for (NSDictionary *eventDict in events) {
Get Array of
Earthquakes
91
92. NSDictionary *jsonDict = (NSDictionary *) objectFromJSON;
if (jsonDict) {
NSArray *events = [jsonDict objectForKey:@"features"];
if (events) {
for (NSDictionary *eventDict in events) {
If Array/JSON is valid
92
93. NSDictionary *jsonDict = (NSDictionary *) objectFromJSON;
if (jsonDict) {
NSArray *events = [jsonDict objectForKey:@"features"];
if (events) {
for (NSDictionary *eventDict in events) {
Iterate over it
93
101. NSFetchRequest *fetchRequest =
[NSFetchRequest fetchRequestWithEntityName:
NSStringFromClass([Earthquake class])];
[fetchRequest setFetchLimit:1];
NSPredicate *eventInfo =
[NSPredicate predicateWithFormat:
@"location = %@ AND date = %@",
eventLocation,
eventDate];
[fetchRequest setPredicate:eventInfo];
NSError *fetchError=nil;
NSArray *existingEventsMatchingThisOne =
[context executeFetchRequest:fetchRequest error:&fetchError];
And run it
101
102. if ([existingEventsMatchingThisOne count]==0) {
//Didn't find one already, make a new one
NSManagedObject *newManagedObject =
[NSEntityDescription insertNewObjectForEntityForName:
NSStringFromClass([Earthquake class])
inManagedObjectContext:context];
[newManagedObject setValue:eventLocation forKey:@"location"];
[newManagedObject setValue:eventDate forKey:@"date"];
[newManagedObject setValue:eventLat forKey:@"latitude"];
[newManagedObject setValue:eventLong forKey:@"longitude"];
[newManagedObject setValue:eventMagnitude forKey:@"magnitude"];
[newManagedObject setValue:eventWebPath forKey:@"webLinkToUSGS"];
}
connectionDidFinish
Loading 6/n
102
103. if ([existingEventsMatchingThisOne count]==0) {
//Didn't find one already, make a new one
NSManagedObject *newManagedObject =
[NSEntityDescription insertNewObjectForEntityForName:
NSStringFromClass([Earthquake class])
inManagedObjectContext:context];
[newManagedObject setValue:eventLocation forKey:@"location"];
[newManagedObject setValue:eventDate forKey:@"date"];
[newManagedObject setValue:eventLat forKey:@"latitude"];
[newManagedObject setValue:eventLong forKey:@"longitude"];
[newManagedObject setValue:eventMagnitude forKey:@"magnitude"];
[newManagedObject setValue:eventWebPath forKey:@"webLinkToUSGS"];
}
If there isn't already
one
103
104. if ([existingEventsMatchingThisOne count]==0) {
//Didn't find one already, make a new one
NSManagedObject *newManagedObject =
[NSEntityDescription insertNewObjectForEntityForName:
NSStringFromClass([Earthquake class])
inManagedObjectContext:context];
[newManagedObject setValue:eventLocation forKey:@"location"];
[newManagedObject setValue:eventDate forKey:@"date"];
[newManagedObject setValue:eventLat forKey:@"latitude"];
[newManagedObject setValue:eventLong forKey:@"longitude"];
[newManagedObject setValue:eventMagnitude forKey:@"magnitude"];
[newManagedObject setValue:eventWebPath forKey:@"webLinkToUSGS"];
}
Make a new Object
104
105. if ([existingEventsMatchingThisOne count]==0) {
//Didn't find one already, make a new one
NSManagedObject *newManagedObject =
[NSEntityDescription insertNewObjectForEntityForName:
NSStringFromClass([Earthquake class])
inManagedObjectContext:context];
[newManagedObject setValue:eventLocation forKey:@"location"];
[newManagedObject setValue:eventDate forKey:@"date"];
[newManagedObject setValue:eventLat forKey:@"latitude"];
[newManagedObject setValue:eventLong forKey:@"longitude"];
[newManagedObject setValue:eventMagnitude forKey:@"magnitude"];
[newManagedObject setValue:eventWebPath forKey:@"webLinkToUSGS"];
}
Set all its attributes
105
106. // Save the context.
error = nil;
if (![context save:&error]) {
// stuff
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
connectionDidFinish
Loading 7/n
106
107. // Save the context.
error = nil;
if (![context save:&error]) {
// stuff
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
Save and
check for errors
107