iOS 8 HealthKit Santiapps Marcio Valenzuela

Saving HealthKit Data & Closures

This code bit saves: healthKitStore.saveObject(bmiSample, withCompletion: { (success, error) -> Void in if( error != nil ) { println(“Error saving BMI sample: \(error.localizedDescription)”) } else { println(“BMI sample saved successfully!”) } }) The method signature is: saveObject(object: HKObject!, withCompletion completion: ((Bool, NSError!) -> Void)!) This method takes an HKObject which is bmiSample and it takes a completion closure which itself takes a bool & error and returns void. So in our method call, we pass in the bmiSample as the HKObject and for the success and error completion block we say: if error is NOT nil then log that error’s description, else log that the bmiSample was saved successfully.  … Read More

Continue Reading
Wifi Communication Arduino Santiapps

Arduino (IoT): Simple Tutorial WiFi CC3000 Arduino Shield

Tutorial WiFi CC3000 Arduino Shield En este tutorial exploramos la shield original de Arduino, WiFi, CC3000.  Esta acaba de ser reemplazada (Nov 2015) por la WiFi 101.  Veremos esa en tutoriales futuros. Ahora veamos los componentes requeridos. Requisitos: Computadora (mac) Arduino UNO Arduino WiFi Shield CC300 Arduino IDE (https://www.arduino.cc/en/Main/Software) Las shields son muy practicas y fáciles de usar.  Simplemente se conectan sobre los headers de la Arduino UNO.  Cuidado porque hay shields para distintas placas.  Es decir que una shield es especifica para la UNO y no funciona sobre la MEGA y vv. Ya conectada podemos repasar el código rápidamente para montar un servidor que muestre datos de sensores análogos (o digitales)… Read More

Continue Reading
Ethernet Arduino Santiapps

Arduino (IoT): Simple Tutorial Ethernet W5100 Arduino Shield

Tutorial Ethernet 5100 Arduino Shield En este tutorial exploramos la shield original de Arduino, Ethernet, W5100.  Tambien esta la Arduino CC3000 WiFi, la cual acaba de ser reemplazada (Nov 2015) por la WiFi 101.  Veremos estas en tutoriales futuros. Ahora veamos los componentes requeridos. Requisitos: Computadora (mac) Arduino UNO Arduino Ethernet Shield W5100 Arduino IDE (https://www.arduino.cc/en/Main/Software) Las shields son muy practicas y fáciles de usar.  Simplemente se conectan sobre los headers de la Arduino UNO.  Cuidado porque hay shields para distintas placas.  Es decir que una shield es especifica para la UNO y no funciona sobre la MEGA y vv. Ya conectada podemos repasar el código rápidamente para montar un servidor que muestre… Read More

Continue Reading

HealthKit for iOS8: Part 7

4. CoreData for other non-health stats You made it to the end!  Ok, so we are basically going to be adding another store to our app and reading and writing data to THAT store as well. First let’s add a new tab and make it a UITableViewController as well.  It will have dynamically populated cells. Now embed it!   Your final storyboard should look like this:   Add a new Swift class called Swimming Data and set that new UITableViewController scene to its class.  Make that class file look like this: import Foundation import UIKit class SwimmingData: UITableViewController { } Now we must add CoreData.  To do this we need to… Read More

Continue Reading

Implicitly Unwrapped Optionals

As an ObjC programmer, I despised the introduction of Optionals in Swift. However, I jumped on the Swift bandwagon on Day 1. So I understood the basic concepts: If a value may at some point not have a value, declare it as optional. If a value has been declared optional, you must test its contents. You can test with if == nil You can if let test Or you can force unwrap I also read about implicitly unwrapped optionals but I confused them with force-unwrapping.  It also threw me off about when and what to use them for. Recently I’ve been working on an app that involves a dance between… Read More

Continue Reading

HealthKit for iOS8: Part 2

So you got past the intro and learned about the health store and how we need authorization from the user in order to have read and write access to certain properties.  Now that the user trusts your app, let’s learn how to interact with the health store. 1. HKObjects and the health store Before we get into reading and writing, let’s get to know HKObjects.  Here is the class tree: As you can see, HKObjectType inherits directly from NSObject.  You can basically have 2 types of HKObjects; HKCharacteristic and HKSample -Type.  HKCharacteristicType doesn’t change over time whereas HKSampleType does change, such as calories consumed, calories burnt, Glucose levels etc.  Let’s… Read More

Continue Reading

HealthKit for iOS8: Part 1

Intro: What it’s for?   HealthKit is a framework that allows you to store health data to a persistent store on the users device.  We will begin with an app from Part 1 but we will take some detours that are important to understand so bare with me. The first steps are: – Create a tab bar application in Swift for iPhone Only – Rename First and Second view controllers to Profile and Journal and make them UITableViewControllers – In Capabilities turn on HealthKit HealthKit, (HK), requires permissions to access the health store since most of this data is considered confidential.  So to do this, move over to the AppDelegate.swift.… Read More

Continue Reading

Swift Closures Quick Reference: Part 3

Now let’s write our own closure! func fetchMostRecentDataOfQuantityType(quantityType: HKQuantityType, withCompletion completion: ((mostRecentQuantity:HKQuantity?, error:NSError?) -> ())? ) { let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) [timeSortDescriptor], resultsHandler: { (query:HKSampleQuery!, results:[AnyObject]!, error:NSError?) -> Void in let query = HKSampleQuery(sampleType: quantityType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor]) { query, results, error in if completion != nil && error != nil { completion!(mostRecentQuantity: nil, error: error) return; } let resultsArray = results as NSArray? var quantitySample: HKQuantitySample? = resultsArray?.firstObject as HKQuantitySample? var quantity: HKQuantity? = quantitySample?.quantity if completion != nil { completion!(mostRecentQuantity: quantity, error: error) } } self.healthStore?.executeQuery(query) } Notice we declare a function that takes a quantityType parameter and a completion parameter.  The… Read More

Continue Reading

Swift Closures Quick Reference: Part 2

Let’s analyze some useful applications of closures in everyday code! Ok so let’s take a look at a real life function that uses a closure.  A typical closure is a completion handler.  A completion handler is a parameter, just like any other, that is passed into a function as a closure.  When that code gets executed, the completion handler gets filled.  Then your function will use the value of that completion handler to do something useful. Here are some typical uses of closures in API’s.  The typical one is UIView.animateWithDuration.  Open Xcode and start writing UIView.anim… and it will autocomplete for you with this: UIView.animateWithDuration(<duration: NSTimeInterval>, animations: <() -> Void()… Read More

Continue Reading

Swift Closures Quick Reference: Part 1

Blocks/Closures are confusing!  They’re confusing because its a bit abstract.  Most tutorials cover how a block is declared and used. Sometimes blocks or closures can me even more confusing… A block is a bunch of code wrapped up in a {}. You can 2 either of 2 things with them: A.  You can assign that block of code to a variable. (this is where completionHandlers, also a confusing concept, fit in) B.  You can use that block of code directly Let’s take a look at assigning it to something.  No doubt you have seen a construct like: var someName = “Mars” or var hisAge = 39 This would be considered hardcoding… Read More

Continue Reading

Swift is Confusing: Classes, Structures, Designated Initializers, Instance Methods, Type Methods, Functions, Methods, Convenience Initializers & External Parameter Names

Class vs Structs Both: Store values, initialize, subscripts, extensible & protocol Class can inherit, de-initialize, reference counting & typecast Functions vs Methods Methods are FUNCTIONS INSIDE A CLASS Functions can be inside or OUTSIDE A CLASS! Cannot use functionName(param1,param2) to call a function declared inside a class {} Methods: It is implicitly passed the object for which it was called It is able to operate on data that is contained within the class Instance Methods vs Type Methods (Instance Method vs Class Methods I think) Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for… Read More

Continue Reading
Swift Optionals Quick Reference for Newbies by Santiapps.com

Swift Optionals Quick Reference

Optionals confuse me so I wrote this post and hope it can be of some help. OPTIONALS Takeaway #1: Optionals are used to declare a variable but are not assigned a value at start Takeaway #2: Optionals contain a Some or None value, they DONT contain a String or Array or whatever else. Takeaway #3: Therefore we MUST unwrap the value of an Optional to see what the prize is 🙂 In other words, to access its value! Takeaway #4: DECLARATION OPTIONS A) Using the following syntax: var someVar? – You will mostly use this… B) Using “var someVar!” <Implicitly unwrapped> – Unfortunately UIKit & other Apple frameworks will use a lot of… Read More

Continue Reading

Why, oh Why, did Apple take away ARC just to give us Optionals!?

I’m having trouble understanding optionals so here is a shot at explaining them. 🙂 var thisIsAnInt: Int Simple, this is an Int variable declaration. var couldBeAnInt: Int? This on the other hand is an optional variable declaration. This optional declaration doesn’t mean: “this is an int, which is optional”. It reads more like: This is an OPTIONAL variable.  It’s a type of variable in and of itself.  Its NOT NECESSARILY an Int.  It just may or may NOT contain an Int”. Woah! Ok so what is it for and when do you use it.  Well that part seems simple enough: If that variable can or could or may be nil… Read More

Continue Reading

iOS : Swift : Blocks = Closures

I’ve never really liked blocks in ObjC. When Swift came out it made things more complicated for me because I’ve never really liked C either. Finally when I had to deal with closures in Swift, well that’s just gonna piss a lot of people off! After a few days reviewing tons of material online, and I mean TONS!  I came to understand this: The only C-like exposure I had prior to ObjC was a little PHP.  So that allows me to understand a function, which is the equivalent of a method in ObjC: DECLARING func sayHello( ) {      println(“Hello World”) } CALLING sayHello( ) RESULT Hello World Even… Read More

Continue Reading

iOS7 Custom Transitions

iOS7 Series –Custom Transitions There is a hierarchy of actors you need to visualize here.  It goes a little something like: A TransitioningDelegate An AnimatedTransitioning A ContextTransitioning The VC you start out with and that will call the transition will adopt the first protocol, the TransitioningDelegate Protocol.  The purpose of doing so is to obtain the authority to manage the entire transition process. You will then create a Transitioning class which we can call the Transition Manager.  This class will adopt the AnimatedTransitioning protocol.  The purpose of this protocol is to animate the transition. The Transition Manager class receives all the necessary information from the Transitioning Context (a protocol adopted… Read More

Continue Reading

Business of iOS Apps

I keep reading articles or watching videos of iOS businesses who made it and they share their wisdom of the Common 10 Mistakes iOS developers make. Guess what? Most of those mistakes, although they are worded as developer concepts, they are really business concepts. Common Mistakes: Don’t need a marketing guy. Don’t need a business guy. Don’t need a business perspective. Usually worded as, I thought I would get rich quick, or Im looking for a one hit wonder, or Im a great programmer and I thought that was enough. Well guess what, if you are going to sell something and make more than 99c for it, its gonna need… Read More

Continue Reading
NSURLSession vs NSURLConnection by Santiapps.com Marcio Valenzuela

Fetching data from an iOS app – The new NSURLSession API

Ok, this is gonna be short, I promise! 🙂 Do you remember those apps you’ve got stored away or the ones you are working on that fetch data from the web with a NSURLConnection? Time to update them, here’s how. Basically you have a method that calls a web fetch and is somehow signaled to use that received data to refresh a UI. If you used NSURLConnection sendAsynchronousRequest:, you have the issue that it blocks the main thread. It does carry out requests asynchronously from each other, but each request does indeed block the main thread since it is carried out in the main queue. Alternatively, you can use a… Read More

Continue Reading

Creating a Menu in SpriteKit

Cocos2d has a easy to use CCMenu object to which you add CCMenuItems.  In SpriteKit however, you are back to UIKit objects.  This doesn’t not mean its more complicated, its just different :-).  You will need to create a UIControl such as a button or you can use SpriteKit’s SKNode to create the visual object onscreen: SKLabelNode*  someNode = [SKLabelNode labelNodeWithFontNamed:@”Chalkduster”]; [someNode setText:@”Play Game”]; [someNode setPosition:CGPointMake(CGRectGetMidX(self.frame)+5,CGRectGetMidY(self.frame)-40)]; [self addChild: someNode]; Now you simply connect the object action to some event like so: for (UITouch *touch in touches) { CGPoint location = [touch locationInNode:self]; if ([someNode containsPoint:location]) { SKTransition* present = [SKTransition revealWithDirection:SKTransitionDirectionDown duration:1]; GameScene* gameScene = [[GameScene alloc] initWithSize:CGSizeMake(1024, 768)]; [self.scene.view… Read More

Continue Reading

Swift Tutorial II

Ok so in the first tutorial we covered let, which is the keyword for defining constants. let thisBeAConstant = 3.141 Now we are going to cover variables, which use the var keyword like so: var thisVariable = time Notice 2 things about Swift: 1) We don’t use ; at the end of a line.  That’s just weird 🙂 2) We don’t have to specify the type.  The type is inferred by whatever value you pass in, so: var someString = “this is a string” var someInteger = 5 So Swift is kinda smart.  Now let’s meet some old friends “Hao jiu bu juan” ARRAYS var energies = [“solar”, “wind”, “fossil”, “this is a… Read More

Continue Reading

Comment Coding – Coding for Visual Learners

I’ve mentioned this in my online courses as well as classroom courses and its usually overlooked.  I think its an important design technique for those of us who are Visual Learners. What’s a Visual Learner? Many people, prime examples are asian students, are great at math because they are quick to grasp abstract tasks.  They can read a sentence or paragraph and understand everything the first time.  Not me! I’m the kind of person that has to read concepts 10 times over and still have trouble applying it.  I need visual representations of concepts in order to understand them.  As a matter of fact, I review iOS and Cocos2D books and… Read More

Continue Reading

Creating a simple UICollectionView in iOS

Steps 1) Create Master-Detail Application & Replace the MasterViewController First we want to create a Master-Detail Application just because it sets up a Master-Detail relationship even though thats the first thing we are going to break :).  So go ahead and create a new project in XCode4 based on a Master-Detail Application type.  Use ARC, Storyboards and CoreData because we will use CoreData to store information.  Your storyboard should look like this: Now select the Master scene until its highlighted in blue and delete it with the Delete key.  We simply replace it by dragging in a UICollectionViewController onto the storyboard in its place.  This places a UICollectionViewController scene with… Read More

Continue Reading

iOS7 – UIKit Dynamics

iOS7 Series – UIKit Dynamics   Incorporating UIKitDynamics into your app is pretty simple!  The great thing about it is that you really get the most bang for your buck because the end result has a really big WOW Factor which is certain to impress your users.  Let’s take a quick conceptual drive around UIKitDynamics. First we adopt the protocol into the ViewController which will implement UIKitDynamics, why?  Well because the objects which will be animated in the end will have to send back a lot of signals like “Hey, I collided with a boundary” or “hey I just hit somebody else and I was going this fast, in this… Read More

Continue Reading

iOS Smarties :)

Everyone loves Smarties!  And much the same way Smarties Candies make you smarter… today we are talking about Code Snippets that make you….er Smarter!  More than a source of cut/paste Objective C source code, this is meant to be a quick reference.  As such, some of these will be incomplete and I will be filling them up as I go along.  1)   UIAlertView UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle:@”No hay farmacias” message:@”Favor cambie sus parámetros” delegate:self cancelButtonTitle:@”Cancelar” otherButtonTitles:@”Ok”, nil]; [internetAlert show]; 2)   NSNotification //1. Register as observer of notifications in viewDidLoad [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@”TestNotification” object:nil]; //2. NSNotifCtr CLEANUP in viewDidUnload [[NSNotificationCenter defaultCenter] removeObserver:self]; //4. Post notif to NSNotif in… Read More

Continue Reading

iOS7 Sprite Kit for Game Design for iPhone & iPad

iOS 7 Series – Sprite Kit Welcome to iOS7 and to start off, I want to kick things off with SpriteKit.  Although it deals with video games, many companies are using iOS apps as a marketing tactic to engage their users in an effort to promote their products. SpriteKit is the most prominent feature in iOS7 so we’re going to take a quick tour.  Go ahead and create a New Project in XCode5 and select the SpriteKit template (the bottom right icon): Click next and fill in your project data.  Once you are in the main XCode window notice we have the following files in the Project Navigator: 1)   AppDelegate… Read More

Continue Reading

First Android App – Part 6

My First Android App Now we are going to receive the input of this message and use the button to send it. To do so, edit your Button declaration to look like this: <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”@string/button_send” android:onClick=”sendMessage” /> We are simply telling it to respond to the onClick button action by calling the sendMessage method. So we must declare this method in code, of course.  Open your MainActivity.java file and add the following: /** Called when the user clicks the Send button */ public void sendMessage(View view) { // Do something in response to button } We are declaring a public method that returns void, is called sendMessage and… Read More

Continue Reading

How to create an app – Not programmatically

A fellow coder asked: “How does one go about developing an app from scratch?  Where does one start?” My response follows: Some will say its a matter of style and you have to find your own. And eventually you will, after a lot of copy-paste programming. I started in 2009 and my first app was a copy-paste of a few different projects. All the app did was connect to the Internet, download XML and parse it into a uilabel. Then I decided to look into more complex app samples. So I downloaded a few from Apple. In particular I remember iPhoneCoreDataRecipes. In hindsight, it was too complex for a beginner… Read More

Continue Reading

ObjC Programming

The Big Picture ObjC is OOP which means objects send messages to other objects. Before getting into messages, let’s define objects. Objects. This is very diverse. An object can be a string, a number, a Boolean, an integer, an array, a dictionary or even one you create yourself. There are any types of objects but let’s start at the root object. The root object is called NSObject. You’ll see references to it in code but you’ll hardly ever use it directly. This is called the root object because it’s the starting point of any object. It’s like Adam and Eve rolled into one and ANY other kind of object in… Read More

Continue Reading

Static Libraries in iOS – Video Tutorial

Libraries is another one of those rather obscure topics for newbie programmers, kinda like Blocks and Delegates/Protocols.  Think of libraries as just that, a resource you can use which doesn’t belong to you.  A loaner 🙂 NOTE: If you need a nice tutorial on Blocks or Delegates, check out: Video Tutorial: Objective-C Blocks Video Tutorial: Objective-C Protocols and Delegates Ok back to our tutorial!  Well a library is a piece of code that you can use (by importing it into your projects) but its not yours, so you can’t really do what you want to that piece of code, except use its functionality.  In this tutorial we will create our… Read More

Continue Reading

OAuth & PKI for Dummies

I’ve been programming for a few years and I’ve heard of PKI and OAuth for a while. I’ve read about it in SSL certificates for servers and even installed certificates. I’ve signed many apps with certificates and I’ve granted access to many others for Facebook or Twitter interaction. I’ve looked around for definitions or explanations lately and came up empty handed. So I’ve put together this article to not only explain it but to try and make sure I DO understand as much as I think I do and point out the parts I DONT! What OAuth is and what isn’t! It’s not a login replacement. Logging into apps is… Read More

Continue Reading

Blocks & Completion Handlers

Think of blocks as c functions: (return type)functionName(input1, input2) { input1 + input2 } and you call it like this: return type = functionName (1,2) Blocks are similar: NSInteger (^mathOperation)(NSInteger x, NSInteger y) = ^NSInteger(NSInteger x,NSInteger y){ return x + y; }; You call it like this: NSInteger sum = mathOperation(1,2); Now imagine how cool it is to, instead of just passing a value to a method (like saying: here is a value, evaluate it), you can pass a whole method to it (like saying: here is something else to do!). Or better yet, here do this but only when you finish doing that! Like, load the users posts or tweets after you finish authenticating him!… Read More

Continue Reading

Creating Reactive Cocoa Xcode project

  Earlier I posted an article on using RAC.  It was a plain vanilla example of using RAC. While I AM working on a second post with more useful examples, I wanted to go over how to ADD RAC to a project.   First, you must have ruby installed.   This means, go to Terminal and type in: which ruby This is what I get: …../.rvm/rubies/ruby-2.1.0/bin/ruby Important to note here that if you don’t have that rvm bit, you might still have ruby.  RVM stands for Ruby Version Manager and for what little I know about ruby, its one of the managers available for ruby but there are others. If… Read More

Continue Reading

Reactive Cocoa in 3 simple steps!

If you made it through installing ReactiveCocoa, via Cocoapods, which required you to have ruby, update it and install Cocoapods and CLT, then you’re already ahead!  So here is RAC.  RAC is used when you need to be notified of something important in your app; completed download, some long asynchronous task like data fetching, parsing or image processing is complete or to update UI such as a completed form produces an active Submit button or an incomplete field yields a red warning sign to the user. How does RAC work? You basically create signals for events you are interested in (like the ones mentioned above) and then you tie those… Read More

Continue Reading

WWDC 2013 Videos of Interest

WWDC 2013 Videos of Interest Introducing Text Kit Advanced Text Layouts & Effects with TextKit Building User Interfaces in iOS7 Custom Transitions Using View Controllers Customizing Your App’s Appearance for iOS 7 Introduction to Sprite Kit Designing Games with Sprite Kit Getting Started with UIKit Dynamics What’s New in iOS User Interface Design Pretty much all the Whats New…

Continue Reading

Apple’s iOS7 and the future of development

Sure iOS7 brings a lot of technological advances. But more importantly, it sets a new precedent in the Software Development industry. Here are a reasons: 1). An Elite development team. Many people complain about Apple shutting out developers by not opening up. It’s funny because their code is open, you just have to be willing to pay. Where disgruntled programmers see disappointment, I see a company filtering an elite team of outsourced developers to keep pushing the envelope where only the savviest survive. 2). An evermore demanding market niche. I downloaded ios7 on Monday like most devs. The first thing I noticed was Skype crashing and Testflight failing to install.… Read More

Continue Reading

Events & Reminders on iOS

  Many apps take advantage of the Events or Reminders on iOS. This is very useful when wanting to give the user the ability to add an event to the calendar or a reminder. This is quite simple to do, so let’s take a look.  Create an NSObject Class to manage all our EventKit stuff and add the following: #import <EventKit/EventKit.h> @property (strong, readonly) EKEventStore *eventStore; @property (assign, readonly) BOOL eventAccess; @property (assign, readonly) BOOL reminderAccess; So far we are simply importing the EventKit, which by the way you must add as Link Library in Target Settings, Summary.  Then we add a property to access the EventStore and some booleans.… Read More

Continue Reading

Cocos2d Tips: Sounds & Text

Professionalize your game by adding sounds and text for menus and labels throughout your game. SOUND To play sounds you need the Sound Engine, which you import into your layer like so: #import “SimpleAudioEngine.h” Then you can just code a method to handle some background music playing: -(void)loadAudio { // Loading Sounds Synchronously [CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID]; [[CDAudioManager sharedManager] setResignBehavior:kAMRBStopPlay autoHandle:YES]; soundEngine = [SimpleAudioEngine sharedEngine]; [soundEngine preloadBackgroundMusic:BACKGROUND_MUSIC]; [soundEngine playBackgroundMusic:BACKGROUND_MUSIC]; } You can see immediately that you can preload the audio in one place and then play it in another. This is great for game performance. This means you can preload audio in the main menu, for example, and then play it when… Read More

Continue Reading

Cocos2d Tips: Design Game Objects for your game

Keep your game classes organized and logically ordered. Create a GameObject class, a GameCharacter class and then subclass these. Its important to keep your Game Objects ordered as well as your code.  The more you order your objects, the cleaner your code will be as well.  A GameObject is anything used in a game from labels to sprites to power ups. Its important to create a base class for all objects because, as a simple example, you want to be able to constrain all game objects to your screen.  Its not unthinkable to believe that at some point you might inadvertently cause a game object to be pushed off screen.… Read More

Continue Reading

Cocos2d Tips: Scrolling, Parallax and wider levels

Wider Levels & Scrolling When you create a game in Cocos2d, your screen measures 960 pixels wide on iPhone4+ and 2048 on iPad. If we want him to move farther to the right then we need to make the level bigger.  Normally we set: levelSize = screenSize; But now we basically wish to make: levelSize = CGSizeMake(screenSize.width * 2.0f, screenSize.height); // levelSize code What we are doing is changing our scene levelSize to 2x the screenSize. Our level is now twice as big and we have a GameScene, which contains a GameplayLayer & a BackgroundLayer with some background image.  We want to add a layer that will scroll in the opposite… Read More

Continue Reading

How Cocos2d taught me iOS and OOP

I started studying iOS in 2009, started studying Cocos2d in 2011.  I never understood how to do things in code for iOS.   It was all a big mystery to me. What do you mean create a button programmatically and add it to the subview and position it and change its attributes?  I can just drag one from the Object Library onto the canvas and put it wherever I want and change its color etc… After a year of using Cocos2d, I know cherish its teachings as I find myself trying to make an app which requires objects such as UIPageControl and UIScrollView and UIImageViews with UIImages.  In doing this… Read More

Continue Reading

Cocos2d Tips: Transitioning between game screens

Let’s learn how to create menu for a cocos2d game and how to move between a menu, the game scene, a level complete scene etc. Eventually your game will grow and you will have to create a clear structure to keep everything organized. As you can see, as with any app, the AppDelegate is the first object called. As such, it is the entry point to your game and will call the very first scene of your game. This means the first scene should probably the main menu which welcomes the user to the game and presents him with options. As you can see from the Cocos2d tips “Creating a… Read More

Continue Reading

Cocos2d Tips: Connect Layers

Games have many layers. The most common example is the main action layer (where the players and enemies are) having to communicate with the HUD layer (which presents score, health and other info) to the gamer. Let’s see how we can communicate between layers. Typically you create a Scene and then a Layer in order to add that Layer as a child to the Scene. Let’s say our Scene.h looks like this: #import <Foundation/Foundation.h> #import “cocos2d.h” @interface Scene1 : CCScene { } @end And our Scene.m looks like this: -(id)init { if ((self = [super init])) { Scene1ActionLayer * actionLayer = [[[Scene1ActionLayer alloc] init] autorelease]; [self addChild:actionLayer z:0 tag:kActionLayer]; }… Read More

Continue Reading

NSOperationQueue & NSInvocationOperation

1. In your main class’ init method call this: operationQueue = [[NSOperationQueue alloc]init]; [operationQueue setMaxConcurrentOperationCount:1]; 2. Then in your viewWillAppear you can call this: [self showLoadingIndicators]; //calls a method which presents loading indicators (optional) [self beginLoadingTwitterData]; // this is the method that fires it all off 3. In your beginLoadingTwitterData you call this: NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(synchronousLoadTwitterData) object:nil]; [operationQueue addOperation:operation]; // creates and adds NSOperation to a queue [operation release]; 4. In this synchronousLoadTwitterData is where you do the heavy lifting: NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:[TwitterHelper fetchInfoForUsername:[twitterIds objectAtIndex:count]]] // this calls for a method “fetchInfoForUsername” which returns an NSDictionary, but to do so, it connects to… Read More

Continue Reading

Top Ten Mobile App Features

Feedback system Responsiveness Do one thing right Socialize & Gamify A few clicks Website match Analytics Off-line Customize user experience It’s a mobile device Every app needs to provide the user with a direct connection to the company’s customer service department Above all an app must be responsive and quick. The best app in the world is useless if it takes too long to open. Great apps do one thing and do it right! If you try to juggle too much functionality into one app, the user gets overwhelmed. The best way nowadays to keep users interested is to Gamify or Socialize. Gamify means give your users that carrot they… Read More

Continue Reading

GrandCentralDispatch & Blocks

GCD helps improve your apps performance and responsiveness by outsourcing processes that require a lot or computing power to the background while keeping your UI responsive.  Normally you might want to do some heavy lifting. Let’s create an Empty Application.  You need to declare a IBOutlet UIImageView *imageView ivar in your appDelegate, make it a property and synthesize it in .m and make the connection in Interface Builder, IB.  In it’s viewDidLoad method put the following code: // Download the image NSURL *url = [NSURL URLWithString:@”http://www.santiapps.com/assets/bbkoko.jpg”]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; NSURLResponse *res = [[NSURLResponse alloc] init]; NSError *err = nil; NSData *data = nil; data = [NSURLConnection sendSynchronousRequest:req returningResponse:&res… Read More

Continue Reading

iOS App or Cocos2d Game Design – Grand Scheme

A lot of programmers that are entering the iOS application or Cocos2d game arena are somewhat confused about the overall scheme of things. They can’t see the forest for the trees. I’m a very visual learner myself, which actually makes me a rather bad programmer. Actually it makes me a bad programmer because I’m slow to pick stuff up. I need to see the big picture and then dive into the details, not the other way around. So I put together a simple image, for visual learners like myself, to understand how things operate. At this moment its a very simple image. I intend to update it constantly in order… Read More

Continue Reading

TexurePacker 3.0.1 is the best tool for sprite sheets

  Spritesheets are a must these days, what with having to include so much eyecandy now that games for iOS are getting so sophisticated.  Even if not for performance issues, spritesheets are great for simply keeping assets organized in a game.  Add to that the easy to use AutoSD option which makes your HD or Retina Display assets as well as the non-Retina assets easy to manage, TP is by far the best tool for the job. Whether you are a newbie or advanced developer, we highly recommend you pick it up asap.  You’ll see how easy it is to manage your assets and export them.  This is a tool… Read More

Continue Reading

Cocos2d Tips: Creating a Menu

You can create a menu by creating label items or image items and passing them to a CCMenu object. A typical MainMenuScene.m file might look like this: -(void)playScene:(CCMenuItemFont*)itemPassedIn { if ([itemPassedIn tag] == 1) { [[GameManager sharedGameManager] runSceneWithID:kIntroScene]; } else if ([itemPassedIn tag] == 2) { [[GameManager sharedGameManager] runSceneWithID:kSecondScene]; } else if ([itemPassedIn tag] == 3) { [[GameManager sharedGameManager] runSceneWithID:kThirdScene]; } else { CCLOG(@”Unexpected item. Tag was: %d”, [itemPassedIn tag]); } } -(void)displayMainMenu { CGSize screenSize = [CCDirector sharedDirector].winSize; if (sceneSelectMenu != nil) { [sceneSelectMenu removeFromParentAndCleanup:YES]; } // Main Menu CCMenuItemImage *playGameButton = [CCMenuItemImage itemWithNormalImage:@”TapMeToPlay.png” selectedImage:@”TapMeToPlay.png” disabledImage:nil target:self selector:@selector(displaySceneSelection)]; CCMenuItemImage *optionsButton = [CCMenuItemImage itemFromNormalImage:@”someImage.png” selectedImage:@”someImage.png” disabledImage:nil target:self selector:@selector(showOptions)]; mainMenu =… Read More

Continue Reading

Library compile error in XCode 4.5 for iOS6 regarding armv7s and armv7

Here are the resources you will need to fix your libraries.a which are not compiling for armv7s, into working compiling libraries: The post on how to do it: http://www.galloway.me.uk/2012/09/hacking-up-an-armv7s-library/ An article on how to modify your $PATH on your mac: http://www.tech-recipes.com/rx/2621/os_x_change_path_environment_variable/ Another article on how to edit your .profile hidden file: http://www.tech-recipes.com/rx/2618/os_x_easily_edit_hidden_configuration_files_with_textedit/ And this is the lowdown: You will basically have to create the .sh file & .c file mentioned in Matt’s post.  He then explains how to compile the .c and chmod the .sh. Then you must add these files to your path by either creating a .profile or adding this line to your existing .profile: PATH=$PATH:$HOME/afolderwhereyouplacedyourabovefiles # Add to PATH… Read More

Continue Reading

NSOperation

Lets say you are not only downloading tweets (text) from the web, but actual chunks of raw data, such as images. You may have a method that returns a UIImage, such as: -(UIImage*)cachedImageForURL:(NSURL*)url{ //Preferably look for a cached image id cachedObject = [cachedImages objectForKey:url]; if (cachedObject == nil) { //set loading placeholder in our cache dict [cachedImages setObject:LoadingPlacedholder forKey:url]; //Create and queue a new image loading op ImageLoadingOp *operation = [[ImageLoadingOp alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)]; [operationQueue addOperation:operation]; [operation release]; } else if(![cachedObject isKindOfClass:[UIImage class]]) { //were already loading the image, dont kick off another request cachedObject = nil; } return cachedObject; } Except notice this time the operation is not… Read More

Continue Reading

No free lunch…

I started coding in iOS since 2009.  I do it part time because I have a full time job, so I dedicate about 3 hours a day, 5 days a week. I am a tech guy, always have been.  Studied Biochemistry and picked up ASP, PHP and moved into iOS.  But because I live in a country where technicians are highly undervalued, I got my MBA in 2000.  So I know a thing or two about how to run a business. So when I started meeting indies in 2009, I approached them and said, “I have some ideas for an app, is anyone interested in working with me?”.  Their response… Read More

Continue Reading

iOS Indie Developer/Programmer Evolution

These are just random thoughts on what I believe are the pros and cons of coding an app vs a game.  The reason why I am writing this is actually because I find myself in the same predicament.  I’ve been coding crap for the past 3 years and I believe its time to make something “significant”. At first I thought, I’ll code a bunch of apps and even though they might not be Top Pick apps, they will be enough.  Even if they only make about $5-$10 a month,  I may be reaping $100 a month which sounds cool.  I even got into the whole iAds thing and thought it… Read More

Continue Reading

Cocos2d Tips: Animations and image sizing

So you have some art but don’t know how to properly size it for the iPad or iPhone in their 2 versions (retina and non-retina display)! Let’s learn about image sizing and how to use these images in animations for your game objects (player, enemies, power ups or simple eye candy). Before we even get into creating animations, we need to clear up the sizing issue.  Currently there are 4 screen sizes: iPhone NonRetina = 480 x320 iPhone Retina = 960 x 640 iPad NonRetina = 1024 x 768 iPad Retina = 2048 x 1536 This means that when creating art for a game, you will go bonkers sizing images… Read More

Continue Reading

Cocos2d Tips: How to design a game coding strategy

Know you know quite a bit, enough to make a game. Do you know how and where to start? Let’s look at how to start coding your action layer, what code to put in what methods and how to keep your update method clean and tidy. When I started coding, and unfortunately most of my current projects are still coded that way, I simply opened up Xcode and started coding.  iOS apps are a bit better because you can use the “hooks” methods they come with such as viewDidLoad and cellForRowAtIndexPath etc.  Games are a bit more confusing because you are given an empty slate.  At least in Cocos2d you… Read More

Continue Reading

How to Read iOS or Mac OS Programming Documentation

The toughest part for me to get started was reading the Apple Documentation on iOS or MacOS. When I got into more APIs it got more complex. You need to understand how to read API or proprietary code documents in order to understand how to create a piece of code, connect to web services or debug changes in code. You will very often see the term DEPRECATED, which means a particular method name is no longer used. This is very important so let’s take a look at Apple Docs first: This tells us that the object of type NSArray has many methods that you can call on it. They may… Read More

Continue Reading

Passing Data Example

Delegates or Properties, take your pick. PROPERTIES Class A (ViewController) wants to communicate with Class B (ViewController) Before calling Class B, do the following: In Class B, create a @property NSString* receivedValue; In Class A, #import Class B then in the method that calls B (either prepareForSegue or didSelectRowAtIndexPath or some method where you present Class B view controller, do the following: Class B *calledVC = alloc/init calledVC.receivedValue = ‘whatever value you want to pass’; then call Class B VC Done!   DELEGATES Let’s say Class B wants to notify Class A that something has finished.  In Class B add this above your @interface: @protocol YourDelegateProtocol <NSObject> – (void)itemWillBePassed; @end… Read More

Continue Reading

NSCoding & NSUserDefaults to store something simple…

Lets say you created an app which lets you select a person from the Address Book and you wish to set that person as the default user to use each time you launch the app. You want to store that preference in NSUserDefaults. If there is a lot of data to that person, you probably don’t want to store each key, key by key…This is where you can modify your NSObject class to conform to NSCoding and quickly save & load your data. 1. In you NSObject Class add theprotocol. @interface CustomObject : NSObject <NSCoding> 2. Now add these 2 methods to your NSObject Class: – (void) encodeWithCoder:(NSCoder*)encoder; – (id)… Read More

Continue Reading

How to mask a UIImage in iOS

– (void)viewDidLoad { [super viewDidLoad]; UIImage *imageToMask = [UIImage imageNamed:@”koko.jpg”]; UIImageView *imageToMaskImgView = [[UIImageView alloc] initWithImage:imageToMask]; CGRect imgRect = CGRectMake(0, 0, imageToMaskImgView.frame.size.width, imageToMaskImgView.frame.size.height); UIView *maskMaster = [[UIView alloc] initWithFrame:imgRect]; [maskMaster setBackgroundColor:[UIColor whiteColor]]; [maskMaster addSubview:imageToMaskImgView]; UIGraphicsBeginImageContext(maskMaster.bounds.size); [maskMaster.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSLog(@”%@ is the view image”, viewImage); UIImage *bFooImg = [UIImage imageNamed:@”blackapple.png”]; self.myPic.image = [self maskImage:bFooImg withMask:viewImage]; } – (UIImage*) maskImage:(UIImage *)image withMask:(UIImage *)maskImage { CGImageRef maskRef = maskImage.CGImage; CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef), CGImageGetHeight(maskRef), CGImageGetBitsPerComponent(maskRef), CGImageGetBitsPerPixel(maskRef), CGImageGetBytesPerRow(maskRef), CGImageGetDataProvider(maskRef), NULL, false); CGImageRef masked = CGImageCreateWithMask([image CGImage], mask); //memman CGImageRelease(mask); CGImageRelease(maskRef); return [UIImage imageWithCGImage:masked]; }

Continue Reading

Cocos2d Games: PhysicsEditor & TexturePackerPro

Getting an app from idea to finished product is quite a drawn-out process.  As programmers we rarely accept the fact we need help, but thats when tools like these come in.  Tools like PhysicsEditor & TexturePacker are perfect for speeding up the development process of games so that you can focus on the tasks that matter most, the tasks that make a game a winner; game logic. Pick up these tools today, trust me, your expectations will be more than surpassed! http://www.texturepacker.com – The sprite sheet creator turns chaos into order http://www.physicseditor.de – Edit your physics shapes with ease

Continue Reading

Random yet helpful tips for Xcode 4.3.1

I’ve been learning a lot about tools for developing iOS apps and its amazing how much these tools, when you learn how to use them, can help you: Source Control Snippets Edit in Scope Speech Assistant Appirater TestFlight SDK Let’s look at these one by one: Source Control. This tool is for creating “Time Machine” like versions of your project as you progress through your project and make changes to it. The idea is two-fold: (a) Keep important subversions, i.e. version 1.0, 1.0.1, 1.0.5, 1.1.0 etc of your project as you make changes to it. And (b), share those versions with a team of developers so that you all have… Read More

Continue Reading

XCode & Git

Ok, i just started getting my feet wet in this but here is the scoop! Git is a versioning technology which allows you to create multiple versions of your project much like TimeMachine on your Mac.  The whole point behind it is that at any time you can go back to a specific project mod and retake it from there. The first step is to GITTIFY your folder.  You can either do this manually from the command line or from Xcode by creating a new project and check marking the Use Git Repository option.  Since you are using Xcode simply check the box for Git in your new project. Now… Read More

Continue Reading

Use a simple NSNotificationCenter alert

The idea behind this is to notify one object/class of another object/class’ action. Thus you need the following: 1. A Class (A) whose object will register to receive notifications (be notified). 2. A Class (B) whose object will be doing something and when it finishes, must notify the other (post notification) Receiving Class A This class must cleanup its listening task so that when it is no longer active, the NSNotificationCenter will not waste time and resources notifying it about events it was once interested in. To do this simply add this to your dealloc method: //1. NSNotifCtr CLEANUP in viewDidUnload or dealloc [[NSNotificationCenter defaultCenter] removeObserver:self]; This class must actually… Read More

Continue Reading

AddressBook UI

Have you ever tried to get data fields from the address book and ran into the wonderful world of ABPerson reference only to find it reads like the blueprints to a space rocket? Here is the straight out code on how to do it: //Commented out code fails because the values are NOT STRINGS, but rather NSCFType) //NSString *fone = (__bridge NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty); //self.telLabel.text = fone; //This on the other hand, does work ABMutableMultiValueRef phoneMulti = ABRecordCopyValue(person, kABPersonPhoneProperty); CFStringRef fone = ABMultiValueCopyValueAtIndex(phoneMulti, 0); NSString *foneObject = (__bridge NSString*)fone; NSLog(@”phone is %@”,foneObject); self.telLabel.text = foneObject; CFRelease(fone); //Haven’t tried with URL //NSString *url = (__bridge NSString*)ABRecordCopyValue(person, kABPersonURLProperty); //self.urlLabel.text = [NSString stringWithFormat:url]; //SocialProfiles… Read More

Continue Reading

Santiapps.com: Digital Graphic Design for newbies (noobs)

Wanted to share this tutorial for graphic design noobs that are interested in creating their own artwork for iOS games. You may indeed have some graphic design skills and some much better programming skills but turning your paper art into digital usable art is a whole new ballgame. Visit this tutorial in spanish, since this is a spanish blog: Diseno Grafico para Juegos Digitales (Principiantes)

Continue Reading

Importing Box2D & Chipmunk into XCode

 am up to Chapter 13 and I have just finished RE-building my project because of minor details I may have omitted and Id like to share with you all and perhaps get cleared up: 1. Importing folders. When importing folders into Xcode, which Ive had experience with Coreplot, Facebook, twitter apis, json libraries and more recently Box2D and Chipmunk folders, there is a difference between copying and not copying if needed. I thought I understood the difference but Im not sure now. When adding a folder to your project, you add it via the finder first and then via Xcode. Lets take Chipmunk for example: a. You copy your Chipmunk… Read More

Continue Reading

Box2D – Cocos2d – ObjC Complex Code Design

I got lost with a few kinks added in C10 and the vector stuff and c++ stuff in Ch11.   So Id like to review what is happening by the time we get to the cart that you can move via the accelerometer. 1. Before we only needed to add a cocos2d scene and then a layer to make a screenful of action.   With Box2D we must still create a Scene and Layer but we add the C++ format of Class.h & Class.mm  instead of just .m. We also added a query callback C++ Class that serves the specific purpose of  cycling through all bodies in the [b]box2d world?… Read More

Continue Reading

iOS5 Important Features from 200+ available

I’ve reviewed the latest features on the latest iOS5 on many sites and found over 200 out of which only some are really useful to me.  Id like to share the ones I found most important: 1) Swiping a notification will open the relevant app 2) The fact that those notifications are non-obtrusive to YouTube videos 3) Reminder, Calendar, Contacts, Mail, Photo and Doc Integration to iCould because Gmail makes a mess 4) Twitter Integration 5) Open Camera from lock screen although picture taking with the Vol+ button is only for the 4S I think 6) Cropping, Rotating, Organizing and Red-eye removal on pics directly 7) OTA syncing & Delta… Read More

Continue Reading

Pointers, Leaks, Memory Management…objC

Ive been coding for about 2 years now and i recently understood something which has helped me a great deal so i wanted to share it with you.  First let me just expose my learning path so you can determine if its comparable to yours and decide if this article may be of help or just good for a few laughs 🙂   Little HS and College programming background.  Biochem (heavy math and science background).  Picked up HTML and ASP on my own with books and online sites.  Did that for about 4 years.  Picked up iOS at 3.0 and started out using stanfords free online course and made a… Read More

Continue Reading

Oreilly Learning iPhone Programming

Currently on Ch5 but have a few questions looming in the back of my mind: 1) Why use a tableviewcell to enter data for AddNewCity instead of a UIView with label and description? 2) Just as i thought, tag 777 got me in trouble.  My bad because i added the tag to both the inner component uitextField and the outer component tableViewCell by mistake.  But im wondering  a couple of things: (a) can i tag the entire structure uitableViewCell as i did (without tagging the inner components) and get any component inside it with that tag refrence? (b) why exactly was it not passing the data correctly; because the outer… Read More

Continue Reading

Delegates & Protocols iOS

A complex subject to wrap your head around, i agree!  But its pretty cool once you get a working example going. Let’s think of a game where a lander comes down from the sky (presumably on Mars – since Mars is a hot topic lately) and deploys a  rover.  In Cocos2d, you put all your objects on a Layer object.  This means the layer class is the main class (analogous to a viewcontroller class contains buttons, views, labels, cells etc). You create a Lander object class because you want to re-use it everywhere in the game.  With every new level, you must create a new layer class but you can… Read More

Continue Reading

Local Server Auto Upload XML File to Web Server

hi i made this app called iDashBoardCenter which basically dl an xml file from a web server of your choosing.  the problem is that most users have a local private server with internet connection and a local database.  They want that local server to upload the created xml file to a webserver they also manage. Ive got the code that reads the local db and creates the xml file on their local directory but i have no idea how to upload the created xml file copy to a webserver which they can access. the problem remains that an asp code must be run on the local machine “magically” and then… Read More

Continue Reading

iPhoneCoreDataRecipes Explained…

Im going thru this Apple app and im noting my progress in understanding it.  Any comments are appreciated. black = unanswered questions red = my answers so far blue = partially answered on the blog itself green = less important, design questions maybe… RecipeListTableViewController.m 1) Why @class Recipe and @class RecipeTableViewCell 2)  They adopt a RecipeAddDelegate & NSFetchedResultsControllerDelegate protocols? YES…Ive never seen a protocol before.  I guess the NSFRC protocol class is a UIKit class but i had never seen a customcreated class be used as a protocol…COOL! 3)  Why do we declare showRecipe & configureCell methods but not the add:method or the whole bunch of others…. 4)  When creating… Read More

Continue Reading

json php mySQL iphone webService

Youll be glad to know i got it working. I think this is what a webservice is, maybe ive been calling it something else. Ive got the mySQL db sittin on a server in the cloud. There is a php read.php file and a write.php file. The read php file takes the arguments for user and then reads the mySQL db and returns a json string which iphone reads and presents. The write file takes the arguments input by the user and posts them to mySQL db. So is this it? Now im only missing something that the server can use to update a 3rd updatedread.php file that will read… Read More

Continue Reading

Paparazzi Stanford CS193

I’m starting CS193p this new semester again because the Assignment this time around is Paparazzi, a Flickr client which uses CoreData and it’ll be a good experience! I’ve started with the static view controllers and noticed I was a little rough around the edges in alloc/initting view controllers (mainly nav and tabbar). However I got thru it. Then I moved on to Part 2 where you use the plist file to populate the CoreData model which is where I am currently and am stuck! This time around, unlike the Twitter App, we have to use the plist file to populate the db. I’ve got the object model set up, which… Read More

Continue Reading

iLuvMe took OFF in Feb!!!

The iLuvMe App was a hit in Feb! We are pleased so many of you out there downloaded our app and even happier that you liked it so much to write us with thank-you comments from your valentines who so enjoyed it. Just wanted to drop a note to say you’re welcome and were hard at work on version 2.0 with more features as well as on other apps for other end users such as business, entertainment and more! Santiapps.com will keep you posted when new apps become available. Thank you for your support.

Continue Reading

iLuvMe: The Perfect Gift for that Special Someone ;)

This is a nice little app, perfect for your girlfriend or wife or special someone.  You create a file online based on your special memoirs and love messages.  Then you download the app to your iphone and use it to download the file to your girlfriends iPhone.  Thats it!  All your special memories at the touch of her fingertip.  Its perfect for us guys who struggle to get a gift that has real romantic potential.  This will really impress her and it’ll say I Love You like no other gift.  Be the thoughtful one, be truly caring and loving.  She’ll never forget this.  Check out the reviews at AiAR and check out… Read More

Continue Reading

Presence 4 & Lecture 10

I’ve gotten to Presence 4, I believe Lecture 11. I got some confidence on iPhone programming. I started developing a few iPhone apps and am about to upload my first one to the store. I started back in august and maybe dedicated 1 hr a day for about 4.5 months. I haven’t gotten around to audio or video. I have found the coding protocols in cocoa/objC to be lengthy (declaration, property, synthesize…) but it’s overshadowed by the beauty of the iPhone UI kit. I believe Xcode could be further refined to take care of reptitive coding (declaration, property, synthesize…) and even common tasks like mem managment and even threading; what… Read More

Continue Reading

Presence3:NSThread & NSOperation

Im looking through Presence3, understand the LetsMakeAThread project, its pretty straight forward, detachNewThread creates a separate thread and performSelectorOnMainThread returns you to the MT, but in ThreadedFlickrTableView, whats the deal? beginLoadingFlickrData calls a new invocation operation, which loads synchronousLoadFlickrData: which gets the data from Flickr and returns to MT via didFinishLoadingFlickrDataWithResults: which in turn creates the arrays from the FlickrData. Then cachedImageForURL gets called from the cellForRowAtIndexPath?  And so that same method calls the ImageLoadingOperation which then returns to the main thread via didFinishLoadingImageWithResult:? Is this chronology correct?  The MT gets separated or stopped 2x in this app? Once in beginLoadingFlickrData and then in cachedImageForURL?  The difference being that in… Read More

Continue Reading

Plists, SQLite, Write2Disk, PassingData VC

Im working my way thru Lecture 9. Recapping what ive done, i created 2 Preence2 projects; first i pass data using the custom initWithpassedData: method which didnt let me use the initWithStyle for the tweets table view, and second I used the appDelegate pattern which i dont like cause its really a global variable. So Im looking into KVOs and NSNotifications but they look kinda scary! I started using plists for a couple of projects, found out they can be further structured to no just a simple array or a dictionary with keys and objects, but also kind of a flat db with parents and childs. Ill try using plists… Read More

Continue Reading

Presence2 CLEARED Topics CS193P iPhone

1. Why is Person *twit = [Person *twit]alloc init] yield local declaration error hides instance variable, but twit = [Person *twit]alloc init] works fine? Because Person *object = is used to declare the object for the first time.  So if you call this line in your implementation code, it will give that warning.  Whereas object = works fine because youre just alloc/initing an object after it has been declared in the h file…it must have been declared in the h file or in the imported Class Object File for it to work. 2. NSIndex & indexPath.row knows to get more elements in the array because we passed it a value for… Read More

Continue Reading

Presence 2 Stanford CS193P Strategy

CONCEPTUALLY speaking, we must read the dictionary objects, therefore getting the users name and use it to: 1. populate our Person Object 2. get the count value to set the number of Rows in Section 3. set the cell values to the names of these guys. So far Ive: 1. gotten the filepath 2. check if exists and create array for count 3. initwithdictionary with object@index:count 4. create Person Class Instance alloc/init 5. set my Persons displayName, userName & imageURL to the data from the dictionary on twitter via fetchusername. 6. now i have a person object with 3 usernames. i need the count to set the number of rowsinsection. i tried… Read More

Continue Reading

Memory Management Stanford CS193P iPhone Dev

Im not so clear on memory management; i understand what you create you must release, ok, but when?!  Because i just saw the MyTabBar example which creates ViewControllers, 3 of them i think, programatically, and a few lines down in the same m file, the delegate, the controllers get released.  Release means they get destroyed right?  I guess im not understanding conceptually what actually happens because to me, if you create in line 10 and release in line 20, even saying it sounds stupid to me, but its what i see, the user wont have time to use it :). Or is it because they get created, then added to… Read More

Continue Reading

View Controllers Stanford CS193P iPhone Dev

From looking at the MyTabBar app from Lecture 7 you can see that ViewControllers can be created with IB or programatically, like many other things in Xcode/IB.  The important thing is that in IB its not flexible; the way i see it if you create it in IB youre pretty much stuck with the design but in Xcode you can add things based on variables you get from the user or a data source.  EXAMPLE: 1. I went thru a tutorial from LittleComputers.net where we created a tabBarController with 2 tabs and later on added a NavigationController to one of the tabs.  Basically i dragged a tabcontroller from the IB… Read More

Continue Reading

Presence1 CS193P Stanford iPhone Dev

This was a great assignment for me.  I was able to get the PersonListViewController up and running.  I started by: a) Adding the navigationController ivar in the delegate file (h) and adding its view to the window (m) as well as releasing it in dealloc.  Remember its EITHER OR. You EITHER add the nav or tab or table VIEWCONTROLLER as a CONTROL in the XIB FILE. OR you add it in code, by ALLOC/INITING it in the Class File. b) then i added the IBAction in the PersonListViewController (h) and implementing that method (m) by instantiating the PersonDetailViewController, pushing it to the stack and releasing it.  Creating in my mind… Read More

Continue Reading

Stanford Assignment 3 HelloPoly: 1 Control/Multiple Actions

I should have known this from my experience in Flash!  The solution to why it only draws the first polygon is that the same buttons, Increase and Decrease, required multiple, in this case 2, actions, not just one.  Basically you need to define another method, inside the polygonview, which calls setNeedsDispaly.  And hook up the same buttons in the nib file to that method.

Continue Reading