theConspiracyhttp://theconspiracynyc.com!iOS Basic Memory Management http://bytedissident.theconspiracy5.com/2011/08/09/basic-memory-management/2011-08-09 08:06:18 AMWhen developing with iOS it is the developers responsibility to manage the memory usage of their application. This is often a tricky spot that can cause confusion, but is ultimately not too hard to get under your belt.

The two things that happen when memory is mis-managed is:

  1. Memory Leaks
    1. This causes your memory foot print to grow and slows down your app and can potentially lead t your app crashing to being shut down by OS
  2. Over releasing
    1. This happen when we attempt to free an object from memory that is not currently held in memory. This results in a crash.

Memory management follows a pretty simple rule, if you created it you have to release it from memory.

What do you mean by create? We create with the following methods:

  • Alloc
  • Copy
  • New
  • Retain

Each of the above results in allocating RAM for an object.

How does the OS deal with memory management?

The OS keeps track of the retain count of each object and when the retain count of an object gets to Zero the dealloc method is called by the OS and the object is released from Memory.

What is a retain count?

retain count literally means the number of times an object is retained by memory. For instance:

UIView *tempView  = [UIView alloc]init];

The above object would have a retain count of 1. If we then allocated the same object again with copy, retain or new it would grow by 1 each time. For each increment of the retain count we need to release it with  the release method

[tempView release];

tempView = nil -> we add nil here so that we prevent future crashes. If a method is called on a nil object it will not crash.

Every time you call the release method the retain count goes down by 1, until it gets to Zero at which point the OS calls dealloc and it is released from memory. You should never call dealloc the OS will do this for you.

The Autorelease pool.

The Autorelease Pool is a list of objects that the gets released from memory at the end of a code block. An event loop is created Automatically by UIKit for every event iteration, like a tap or swipe.  So for example if you allocate an instance of an object and  send it the autorelease message then as soon as the user interacts the autorelease pool is drained when it completes and it releases your object from memory. Therefore, it’s important not to use autorelease on objects that are required for a longer length of time.

For further study on Autorelease pools I would recommend checking out Apple’s Docs

http://developer.apple.com/library/iOS/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-CJBFBEDI

]]>
Indexed Tables: Part 1 http://bytedissident.theconspiracy5.com/2011/08/02/indexed-tables-part-1/2011-08-02 10:57:53 AMUITableView , Indexed Tables:

Thereʼs a lot you can do with Tables we are going to look at indexed tables and also, reacting to table cell presses. Indexed tables will bring many facets to what you have been studying together and itʼs a very common and useful technique for organizing data. In case you donʼt know what an indexed table is. You see it every time you open your contacts and you get the a-z lettering that helps you quickly navigate your contacts.

To begin with there are 2 delegate methods that are required in order for indexed tables to work:

1.sectionIndexTitlesForTableView

2.titleForHeaderInSection

Before we dive into how this works let me go through how indexing works. Itʼs simple to implement once you understand it, but it pulls in your knowledge of Arrays and how to use them in the real world. The table gets instantiated and 1st UITableView looks for the number of sections in the table, then loops through each section and as it does it looks for the number of cells per section and at that point it populates each Cell. In the case of an indexed table the table will contain as many sections as you have indexes. In the case of an alphabetical index it would have 26 sections. So in order to index a table you would create an Array that would serve as your index array. If you take a look at the sample code I have an array called letters which simply has 26 indexes a-z.

The process that happens for UITableView is as follows:

1. UITableView looks to see how many sections your table contains. in this case it contains [letters count], the number of indexes you are using

2. sectionIndexTitlesForTableView – This methods simply returns the Array you are using for indexing.

3. Then as it loops through each section it hits

4. titleForHeaderInSection. This method returns a string that will serve as the header for that section. The blue band with the letter in it that you are probably used to seeing from other applications

5. Then it hits cellForRowATIndexPath. Here I have put in dummy data. UITableView automatically adds the Index UI for you and your ready to go.

Download Files

]]>
Reading and Writing to plists http://bytedissident.theconspiracy5.com/2011/03/16/reading-and-writing-to-plists/2011-03-16 11:56:50 PM

Property lists otherwise referred to as plists are great mechanisms for storing small to moderate amounts of persistent data in iOS. You can store and retrieve right from Arrays and Dictionaries one line so it is very convenient.

First lets take a look a reading from a plist file. This is really a simple process of below is a step by step.
Step 1:

Determine the path of your file.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"shows.plist"];

Step 2:

Read your file into an Array or with the second line read it into a Dictionary.

NSArray *playlist = [[NSArray arrayWithContentsOfFile:path] retain];
OR
NSDictionary *playlist = [[NSDictionary dictionaryWithContentsOfFile:path] retain];
Writing to a plist:

Step 1:

Determine the path to the file you want to write to;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path2 = [documentsDirectory stringByAppendingPathComponent:@"games.plist"];

Step 2:

With either your Array your Dictionary write your plist.
[games writeToFile:path2 atomically:YES];

]]>
JSON – Quick Start http://bytedissident.theconspiracy5.com/2011/03/16/json-quick-start/2011-03-16 11:46:14 PMJSON Tutorial

This is a quick JSON tutorial. JSON is fast becoming the most popular data format for delivering data t6 mobile and web applications an is used by most major API’s including Facebook, Twitter, You Tube and Flickr to name a few.

Arrays: An array in JSON is enclosed in brackets an each item is separated by a comma:

[0,1,2,3,4];

Dictionaries (Key/Value Pairs): Dictionaries are enclosed in curly braces and each Key Value is separated by a comma and each key’s value has a colon between

{"The Key":"The Value","Another Key":"Another Value"}

Example of an Array of Dictionaries:

[{"First Key": "First Values"},
{"Second Key": "Second Value"},
{"Third Key": "Third Value"}]

I highly recommend using this JSON validator http://jsonlint.com

]]>
Setting up a Tab Bar App, Part 1 http://bytedissident.theconspiracy5.com/2011/03/08/setting-up-a-tab-bar-app-part-1/2011-03-08 03:45:59 PMSetting up a Tab Bar Application in XCode is a really easy process once you get the steps down.  Below is a quick step by step on how to do it.

Step 1
In XCode create a new project
Choose “Tab Bar Application” from the template that Apple provides you with.

Step2
In your “Resources” folder double click on your MainWindow.xib file to view it in Interface Builder

Step 3

When IB is open view your Document (Apple 0). Look in your document and Highlight the Tab Bar Controller View the Tab Bar Controller in your Attributes Inspector (Apple 1). Here you can add as many View Controllers as you would like by pressing the + symbol under the Tab Bar Controller Palette. To Change the Titles that appear in your tab bar buttons simply change the titles here.

a-tb

Step 4

Now you will need to create View Controller and XIB file for each ViewClick File->New File. From your templates choose Cocoa Touch Class->UIViewControllerSubClass. Then name this logically according to your apps navigation. Note: If you check “With XIB interface” XCode will automatically and connect it. I am going to do this by hand.

Step 5

For each XIB(view) you will need to connect its corresponding view controller class. To do this open each XIB in Interface Builder. Navigate to the document window (Apple 0). The hight light the “files owner” and in the attributes inspector add your view controller class under “Class Identity”.

1-tb

Step 6

Then don’t forget to connect your view to your file’s owner like so. If you do not connect your main view your app will crash.

3

Step 7

Finally your MainWindow.xib you will need to set the Nib name in your attributes inspector.

4

That should do it! happy coding.

]]>
Objective C, syntax basics part 1. http://bytedissident.theconspiracy5.com/2011/03/01/objective-c-syntax-basics/2011-03-01 06:50:12 AMWhether you are learning a new programming language or Objetive C is the first language you have ever grappled with getting the basic syntax memorized is a necessity.

Anatomy of instantiating an object:

No matter the object the syntax is uniform

ClassName *instanceName = [ClassName alloc];

[instanceName init];

For convenience you will often this done with nested functions like so

ClassName *instanceName = [[ClassName alloc]init];

What does the above code really do?

1. ClassName declares what Class/Object we are going to instantiate

2. *instanceName creates our instance name, a referential name to the class. The * is a pointer that tells the compiler that the next piece of text is the instance name.

3. = is needed in order for us to set a value to the instanceName

4. [ClassName Alloc] , this says create a space in RAM for this object

5. [instanceName init] , this is the final initialization method call. Nothing happens without it.

Calling Methods/Functions:

[instanceName methodName];

All methods are called by enclosing in brackets instance name then a space then method name.

Instances with parameters are called like so:

[instanceName methodName:parameter];

These basic rules apply to all objects/classes whether created by you or if you are using one of Apple’s APIs like UITextView. I hope this helps.

]]>
Location Tutorial http://bytedissident.theconspiracy5.com/2010/12/06/location-tutorial/2010-12-06 11:35:03 AMThis is a simple tutorial designed to get you moving on using Apple’s Location services in your iOS applications. Below is a quick step by step that should get you up and running quickly. Before we start create a View Based Application in XCode called LocationTutorial.

Step 1:
First of all we need to make sure we add the Core Location framework to our project. To do this ctrl-click or right click on your project Icon and then your application’s target. Then in the right panel choose “Build Phases”
location-2

Then open “Link With Binary Libraries” and press the + symbol. Scroll down the list of frameworks. Then highlight Core Location and click “Add”

loaction-1

Step 2:
In the LocationTutorialAppDelegate.h file of your project import this frame work.
location-3

Step 3:

In your header file you will need to make you sure you add the CLLocationManagerDelegate so that Core Location can return you info as it comes in.

@interface LocationTutorialAppDelegate : NSObject {
UIWindow *window;
LocationTutorialViewController *viewController;
CLLocationManager *locationManager;
}
@property(nonatomic,retain)CLLocationManager *locationManager;
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet LocationTutorialViewController *viewController;

Step 4:
Now in your header file create a property for your CLLocationManager and in your delegates implementation file synthesize your property;

@implementation LocationTutorialAppDelegate
@synthesize window;
@synthesize viewController;
@synthesize locationManager;

Step 5:
Now that your set up is complete you will just need to instantiate the class, set the delegate to self and call the StartUpdatingLocation method.

self.locationManager = [[[CLLocationManager alloc] init] autorelease];
self.locationManager.delegate = self;

Here we can can optionally set the accuracy property
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

Here we start the service
[self.locationManager startUpdatingLocation];

Other accuracy properties:
kCLLocationAccuracyBestForNavigation;
kCLLocationAccuracyBest;
kCLLocationAccuracyNearestTenMeters;
kCLLocationAccuracyHundredMeters;
kCLLocationAccuracyKilometer;
kCLLocationAccuracyThreeKilometers;

Note: Do not forget to release your property in your dealloc method;

Step 6:
Finally you will need to include Core Location’s delegate locationManager method to get the return values from the framework. You’ll notice here that I am converting the newLocation coordinates to strings. It’s up to you to decide what you want to do with your new data.

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(@"%@",[NSString stringWithFormat:@"%3.5f", newLocation.coordinate.latitude]);
NSLog(@"%@",[NSString stringWithFormat:@"%3.5f", newLocation.coordinate.longitude]);
}

Now you will probably want to experiment with a number of things. Just to point you in the right direction take a look at this distance method
CLLocationDistance distance = [newLocation distanceFromLocation:oldLocation];

Download Code

]]>
NSUserDeafaults / Saving User Settings http://bytedissident.theconspiracy5.com/2010/12/02/nsuserdeafaults-saving-user-settings/2010-12-02 08:32:23 AMIt’s a very common practice to save/persist settings, preferences and  login credentials in our applications.  Apple has made this task very easy for us via the NSUserDefaults object. Below is a quick step by step of how to use it.

Step 1:

Instantiate NSUserDefaults:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
Step 2:

Set a default in the following manner, this just your typical objecting setting for a key value pair (dictionary).

[prefs setObject:@"my value" forKey:@"my_setting"];

Synchronize your settings

[prefs synchronize];

Step 3:

Read the preference back later.

[prefs stringForKey:@"my_setting"];

NOTE:

The one thing to pay attention to here is the data type. In this case I am asking for a string, but you may use other data types check out the methods below


- (NSString *)stringForKey:(NSString *)defaultName;
- (NSArray *)arrayForKey:(NSString *)defaultName;
- (NSDictionary *)dictionaryForKey:(NSString *)defaultName;
- (NSData *)dataForKey:(NSString *)defaultName;
- (NSArray *)stringArrayForKey:(NSString *)defaultName;
- (NSInteger)integerForKey:(NSString *)defaultName;
- (float)floatForKey:(NSString *)defaultName;
- (double)doubleForKey:(NSString *)defaultName;
- (BOOL)boolForKey:(NSString *)defaultName;
- (NSURL *)URLForKey:(NSString *)defaultName

Now once you set your NSUserDefault it will be saved to your app and persist between launches.

Download Code

]]>
UIWebView Tutorial http://bytedissident.theconspiracy5.com/2010/11/24/uiwebview-tutorial/2010-11-24 08:22:24 AMAdding a web page to your app is often very useful and quite easy to do. Below is a quick example.

Lets create a view based application as our starting point. Call it WebPage.

Step 1:

Create an IBOutlet for your UIWebView as we do for all UI Objects when using Interface Builder

Header file code:
@interface WebPageViewController : UIViewController {
IBOutlet UIWebView *wView;
}
@property(nonatomic,retain)IBOutlet UIWebView *wView;
@end

M (Implementation File) code:
@implementation WebPageViewController
@synthesize wView;

Step 2:

Open your XIB file in Interface Builder  (if you named your  project according to the project it would be WebPageViewController.xib) by double clicking on it. Drag a UIWebView from your Library onto your View.

Step 3:

Connect your UIWebView to your outlet by dragging the files owner to the UIWebView

webpage1

Step 4:

Make your files owner the delegate fore your web view by ctrl-clicking on your UIWebView and dragging the line to the files owner.

webpage2

Step 5:

Finally in your view controller you will need to add the code to load a web page. This is a simple process you will need to memorize. The UIWebView needs to call its loadRequest method which requires a NSURLRequest object. Here I show how you convert a URL String to a NSURLRequest Object.


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//A URL STRING
NSString *urlAddress = @"http://bytedissident.theconspiracy5.com";

//Create a URL object FROM THAT STRING
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Requst Object CREATD FROM YOUR URL OBJECT
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
[wView loadRequest:requestObj];

//scale the page to the device - This can also be done in IB if you prefer
wView.scalesPageToFit = YES;
}

Download Code

]]>
IBActions / Connecting UI Objects Part 2 http://bytedissident.theconspiracy5.com/2010/11/22/ibactions-connecting-ui-elements-part-2/2010-11-22 04:48:16 PMThis is part 2 of my Interface Builder tutorial. In part I outlined the 3 step process to connecting a UI element added via Interface Builder to your view controller via the creation of an IBOutlet prefaced property. In this tutorial we will look at how to add a target and call a method from that UI element (UIButton) with an IBAction.

As with an IBOutlet we need a way to let Interface Builder find the method you want to add a target and action to. This is done simply in the following steps:

Step 1:

Add a method to your view controller. Lets call it doSomething for the sake of this tutorial. In order for Interface Builder to connect to this we will need to make this method return an IBAction.

In your header file add:

-(IBAction)doSomething;

In your implementation file add:

-(IBAction)doSomething
{
NSLog(@"HEllO");
}

Step 2:

In interface builder ctrl-click on your button and drag a connection from your button to your files owner and choose your method from the menu (screen shot 2) and that’s it. Your connected. Test your code and be on your way.

ibaction1

Ibaction2Download Code

]]>
App Store Economy http://wheresyourmachine.com/?p=392010-01-13 10:53:18 AMI guess that everyone already knows how successful the Apple app store has been, but when you see the data put together in this display by GIGAOM it really hits home. Check it out. Then talk to us about our iPhone Think Tank!!

]]>
Turn Me On http://wheresyourmachine.com/?p=322009-12-06 09:54:04 PMEvery now and then there are certain small signs in innovation that happen that make you stop and take notice
There is something about this new USB wall socket from True Power that really caught my eye. Maybe it is just the fact that a socket has looked the same since I can remember. It kind of reminds me of the rotary to pushbutton transition.
I think I see a new business opportunity for plastic, baby safe usb plugs. Gotta make sure the kiddies don’t stick a fork, or a humping dog, into the new socket!

image.php

]]>