Posts tagged #programming

iPhone App Memory Management - Why Do I Get Errors About Retain Release Dealloc in Xcode 5

In Xcode 4 and Xcode 5 an underrated developer tool for beginners is called ARC (). It simplifies a lot of the code and logic that we used to need to think about when we wrote apps.

Unfortunately, a lot of the code that you'll find on StackOverflow contains release, retain, autorelease, and [super dealloc]. When you try to copy that code into a new Xcode 5 project you'll get Xcode errors complaining about it. For the most part you can remove the extra nested method call to retain, release, autorelease, and you can delete anything that says [super dealloc].

If you want to see some examples I've posted some snippets of code of what you used to write and how it translates with the ARC code. Older projects should be updated to ARC because it makes it a lot easier to add open-source libraries that use ARC, or ARC code files.

Side note: I wrote before ARC was released and it was a royal pain trying to add some extra source code that was designed for ARC at the last minute before an art exhibit at Joe Bean Coffee Roasters. In the near future I plan on converting my app, Artwork Evolution, to ARC to make it easier to integrate some code that I've been using in my newer apps.

Example Xcode 5 Error Messages

NSDate *date = [[NSDate date] retain];

In non-ARC code we needed to explicitly tell the iPhone that we needed to hold onto memory so that we could do calculations or respond to user input. You'll see a lot of code littered with retain calls to make sure the app doesn't crash.

ARC: In ARC code we can remove all of these retain statements and make the code easier to follow and read. 

'retain' is unavailable: not available in automatic reference counting mode
ARC forbids explicit message send of 'retain'

Rewrite the code as:

NSDate *date = [[NSDate date] retain];  // Non-ARC

NSDate *date = [NSDate date]; // ARC

or

NSDate *date = [[[NSDate alloc] init] retain]; // Non-ARC

NSDate *date = [[NSDate alloc] init]; // ARC

Note: With ARC, both [[NSDate alloc] init] and [NSDate date] behave the same. You can make your code more concise by using the static convenience method [NSDate date].

[image release];

Release was used to let the system know that you were done with memory. This allowed the memory to be used for other programs or other parts of your app. If you forgot to do these calls you ended up with memory leaks, and eventually your app would crash because it didn't have any memory to use.

ARC: In ARC code you can safely remove any calls to release.

'release' is unavailable: not available in automatic reference counting mode
ARC forbids explicit message send of 'release'

// Non-ARC
UIImage *image = [UIImage imageNamed:@"BombDodge.png"];
self.logoImageView.image = image;
[image release];

// ARC
UIImage *image = [UIImage imageNamed:@"BombDodge.png"];
self.logoImageView.image = image;

 

[super dealloc];

In non-ARC code we had to make sure to call the super method of dealloc to finish cleaning up our memory. If you didn't do this and didn't release objects that you were finished using you would have memory leaks.

ARC: In ARC code we don't, so you can safely remove those calls in your classes or sample code you copy/paste from StackOverflow. You can also remove any calls to release or objects set to nil.

ARC forbids explicit message send of 'dealloc'
// Non-ARC
- (void)dealloc {
    [super dealloc];
    
    [image release];
    image = nil;
    
    [self closeNetworkConnection];
}

// ARC
-(void)dealloc {
    [self closeNetworkConnection];
}

ARC: There are two special cases that you may want to keep the dealloc method (if it's empty you don't need it).

  1. If you need to close down a network connection, socket, database, etc. You can use the dealloc method as a hook to trigger that action.
  2. If you set any delegate objects that don't use a "weak" property modifier like the UITableView delegate or dataSource, you may want to set those to nil. You can run into situations with KVO or object lifetime where the class you created doesn't live as long as the UITableView class. In that case the UITableView object might send a message to your deallocated object, which can cause a crash.
// UITableView property is not weak!
@property(nonatomic, assign) id dataSource

// Custom dealloc to nil out the property to prevent crashes
- (void)dealloc {
    self.tableView.dataSource = nil;
    self.tableView.delegate = nil;
}

[myObject autorelease];

A lot of times when we worked with memory management, we used the auto release pools, which allowed us to use memory without having to do retain/release methods. There's a convention to how these methods were named, and your using them when you use something like [NSDate date]. The object will be alive for the scope of where it's used, unless you make an explicit retain call.

FIX: With ARC we don't need to worry about these old conventions and can just remove the extra method call to autorelease.

'autorelease' is unavailable: not available in automatic reference counting mode
ARC forbids explicit message send of 'autorelease'
// Non-ARC
+ (MyObject)myObject {
    MyObject *myObject = [[MyObject alloc] init];
    myObject.title = @"A title";
    myObject.on = NO;
    return [myObject autorelease];
}

// ARC
+ (MyObject)sampleObject {
    MyObject *myObject = [[MyObject alloc] init];
    myObject.title = @"A title";
    myObject.on = NO;
    return myObject;
}

Conclusion

When you copy/paste code from old textbooks or StackOverflow you may have to clean up the code to get it to work in the latest versions of Xcode 4 or Xcode 5+.

ARC is Automatic Reference Counting and it saves you a lot of time thinking about who "owns" a piece of memory (to store images, text, numbers, etc) in your apps. You can instead focus on how the logic of the app will work, how it will save data, how it will transition between screens, how it will animate and help the user accomplish a task.

Posted on May 30, 2014 and filed under Programming .

Objective-C Syntax Highlighting with Squarespace 6 using SyntaxHighlighter without Developer Mode

Syntax Highlight for Objective-C on Squarespace 6

Update 6/19/14: This method works for Safari, but it keeps failing in Chrome. I've disabled it for now until I can investigate a better option. The code and method should still work, but the comparisons won't look different below.

I write a lot of code samples and I was using SyntaxHighlighter on my wordpress blog, but since I started using Squarespace I didn't have an easy solution to get it working. I spent the day digging around the internet and found some guides on how to get it to work without the Developer Mode on Squarespace. 

Syntax highlighting is useful because it makes it easier to digest what the different parts of a blog post are. You can easily separate the content from the code because of the coloring. I'll show a comparison with pros/cons and then you can jump to the guide to setup your Squarespace blog.

Code Sample Comparison for Squarespace Blogs

Code Paragraph Style

Here is a code sample without syntax highlighting using the "Code" paragraph style for the monospace font. It's rather buggy to get right in Squarespace 6. You copy paste into Squarespace and the formatting will be off (I have to delete every other newline (return)). Then I have to apply the "Code" tag and reformat again. It's super picky and if you modify the text too much you may have to reformat it.

Pros:

  1. Works out of the box
  2. Don't need to escape "<" characters with <

Cons

  1. Spacing is buggy
  2. Lots of text formatting
  3. Deleting text lines near, in, or around the Code paragraph style can alter the formatting

 

#import "ViewController.h"
@interface ViewController () <UIGestureRecognizerDelegate> {
CGFloat _centerX;
}
@end

@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];

UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftEdgeGesture:)];
leftEdgeGesture.edges = UIRectEdgeLeft;
leftEdgeGesture.delegate = self;
[self.view addGestureRecognizer:leftEdgeGesture];

// Store the center, so we can animate back to it after a slide
_centerX = self.view.bounds.size.width / 2;
}
@end

As you can see it becomes hard to read and really see the code. There is no syntax highlighting and controlling the spacing is manual. I'd have to manually fix each line to get it to indent properly, instead of defaulting to my copy/paste from my code editor.

SyntaxHighlighter Code Highlighting

Here is the same code sample with SyntaxHighlighter. Instead of doing a Text block, I use a Code block with HTML. To learn how to set it up, keep on reading below.

I'll use the

 installation method so that the code is inline with the blog, as opposed to the script method. The script method doesn't work well with RSS readers. Note: If you want your code indexed by Google, you'll want to use 

 to rank higher in search for the code.
                          

Pros

  1. Multiple programming languages supported via brushes.
  2. Respects code formatting/spacing

Cons

  1. Need to escape the < "less-than" characters as < (Find and replace all in the code block)
#import "ViewController.h"

@interface ViewController ()  {
    CGFloat _centerX;
}
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIScreenEdgePanGestureRecognizer *leftEdgeGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleLeftEdgeGesture:)];
    leftEdgeGesture.edges = UIRectEdgeLeft;
    leftEdgeGesture.delegate = self;
    [self.view addGestureRecognizer:leftEdgeGesture];
    
    // Store the center, so we can animate back to it after a slide
    _centerX = self.view.bounds.size.width / 2;
}
@end

SyntaxHighlighter Makes Code Readable on your Blog

Now that you've seen the comparison, let's jump right in and set you up with SyntaxHighlighter on Squarespace 6. You don't need to upload files or enable developer mode to make it work. Instead we can link to already public javascript and css files.

1. Go to your Squarespace Settings Tab > Code Injection > Header

Settings > Code Injection > Header to add custom code to all pages hosted on  your Squarespace domain.

Settings > Code Injection > Header to add custom code to all pages hosted on  your Squarespace domain.

2. Add the following code to get syntax highlighting working for Objective-C, CSS, and javascript. I code in Objective-C, but I needed Javascript and CSS to show the code for this post.

 
 
 
 
 






  

 
 

3. Add a Code block for HTML code, and disable "Display Source". You'll have to hover the mouse on the left side of your "Edit Post" popup window with Squarespace 6. You'll see a "+" to add a new block.

Add a new block by hovering your mouse on the left side of Squarespace

Add a new block by hovering your mouse on the left side of Squarespace

4.  Scroll down in the popup until you find "Code" under the "More" section. Click it to add it. Or you can drag it to a specific position in the layout of your blog post on Squarespace 6.

Scroll down and look for the Code block under the More category.

Scroll down and look for the Code block under the More category.

5. Turn off the "Display Source" option and use the HTML code to have the code work properly.

Add your source code and make sure to replace any "<" characters with the < escape code for proper HTML formatting. If you don't, your source code won't render correctly and you'll see strange things on your blog page.

Disable the "Display Source" and make sure you are on HTML code. All < characters should be replaced with <

Disable the "Display Source" and make sure you are on HTML code. All < characters should be replaced with <

6. Add some sample code to display with syntax highlighting.

Sample code (Copy/Paste to your code block)

#import "ViewController.h"

@interface ViewController () {
    int _x;
}

@end

Output of Sample Code

#import "ViewController.h"

@interface ViewController () {
    int _x;
}

@end

Gotchas:

Code is Editable on Double-Click

The code uses a property to make it easy to copy/paste the full code block. If you want to disable this behavior you can add the code to disable quick-code. If you click off of the text area, it'll jump back to the code. It's a little annoying, but it can make it easier for your readers to copy/paste code from your website to their IDE.

#import "ViewController.h"

@interface ViewController () {
    int _x;
}

@end


How do I Remove Line Numbers?

Set the gutter to false after you set the brush. Include a ; (semicolon) to separate multiple arguments.

Source

#import "ViewController.h"

@interface ViewController () {
    int _x;
}

@end

Output

#import "ViewController.h"

@interface ViewController () {
    int _x;
}

@end

Xcode Copy and Paste Issue with Non-breaking Space Characters -  

Using the default script that I have linked has a bug where when you double click and copy, the code inserts non-breaking space character codes.   or  

To fix this, make sure in the code you placed under Code Injection in Squarespace's settings that you include an explicit white space character for your spaces. You can set this to any character you'd like. Normal spaces will fix the copy/paste issues.


SyntaxHighlighter Can't find brush for: js (etc)

Can't find brush for: js - We didn't uncomment or add the correct language brush for SyntaxHighlighter

Can't find brush for: js - We didn't uncomment or add the correct language brush for SyntaxHighlighter

You'll need to include a new script for each language that you want to support code formatting. I would only include the ones that you need.

You'll get this error dialog when a user loads the page and the brush type isn't supported. (Or if the source file original links you've used no longer exist)

Resources

Let me know if this post was helpful. I spent a lot of time trying to research it and figure out solutions to some of the common problems. You can take a look at the resources that I found helpful.

Connect

  1. Join my iPhone mailing list to keep learning about making iPhone apps.
  2. For more structured learning, signup for my online iPhone app course.
Posted on March 25, 2014 and filed under Programming, Tips .

Top 3 Projects from How to Make an iPhone App for iOS 7 in January 2014

We ran another successful app challenge in my new course How to Make an iPhone App for iOS 7! There were 47 projects submitted for the competition and it was narrowed down to three winners. Each of these students has built an app from scratch and taught themselves Objective-C and iOS app development along the way.

The students started with sketches based on their app ideas, moved to paper prototyping, and then began writing code to bring the app to life. Checkout the project pages and leave some love!

1st Place

Thread List: Embroidery Floss/Thread Manager

by Josh Greco

"There are hundreds of different colored embroidery flosses and it can be difficult to keep track of what you have on-hand versus what you need for any given project. This application aims to simplify this task and help ensure you always have enough of the materials you need.

Features:

  1. Maintain a database of embroidery floss on-hand.
  2. Maintain a database of personal projects and their embroidery floss requirements.
  3. Maintain a database of all available embroidery floss produced by the DMC manufacturer.

My wife is an avid "stitcher" and has thusfar been unhappy with existing apps which advertise similar functionality. If I can make something she can use and enjoy, it stands to reason that others would find it useful."

2nd Place

ClimbNotes

by Trish Ang

"ClimbNotes is an app for rock climbers! More specifically, it's a personal note-taking app for any projects that a climber is working on. A project is a climbing route that requires multiple tries and sometimes long periods of time to complete. 

This app is actually a sub-function of a larger app I'm developing, SuperBeta: an interactive guide for outdoor climbing. Since the functionality is a lot more simple, however, I'm focusing on learning the basics of objective C and also learning how to customize the UI through Xcode. 

Below is an early sketch and a test walkthrough is available here. The functions for ClimbNotes are basically:

  • Add a new route
    A route requires at least one image. You can add a title, a difficulty grading, a quality grading, and tie it to a location. You can also add supplemental information like a description, categorize the type of climb it is, etc. If possible, I'd also like the user to be able to trace the route onto the photo.
  • Take notes on your progress
    On routes you've already recorded, you can make notes for each attempt you make. For example, I can say I tried the route again last Sunday and got two moves further, but still fall around 70% through."

ClimbNotes Video Link

3rd Place

Brewer Note

by Andy Culler

"What's the biggest problem with homebrewing? Forgetting an awesome recipe! From brewday to cracking that first bottle is at least 3 weeks, which is plenty of time to not write it down.  Why not record your recipe as you're brewing, complete with notifications for every step of the way?  BrewerNote brings this all to your phone along with brew history, recipe sharing, and more

Recipes

The recipes section will be used to store the detailed ingredients and steps to brew each recipe that the user inputs.  These will be associated with brews, both current and completed.

Current Brews

The current brews section tracks brews that are currently either being brewed (still in the kettle) or in some stage of fermentation. The main reason that this is important is for timers. These timers include:

  • Hop additions
  • Fermentation stages
  • Carbonation

Completed Brews

The completed brews section is a history of past brews.  This is helpful when, down the line, you crack open an old bottle of brew. So long as it's labeled, this section will allow you to go back and see what ingredients were used, how long it was fermenting, and how long it aged."

Posted on January 29, 2014 and filed under Programming .