Posts written by Matt Mayer
Debugging retain cycles in Objective-C: four likely culprits
Your iPhone app seems to be working fine. But suddenly, it starts to run slow and crashes! You suspect it's memory-related. Here's how to track down and fix issues with retain cycles, which can cause memory not to be released properly.
I'm assuming you are using ARC and iOS5.0+. While ARC simplifies a lot of memory management, it won't spot all retain cycles for you!
First, check you're genuinely dealing with a memory condition. Try to reproduce the crash on a device, and look for crash reports using Xcode > Organiser > Device Logs.
Low memory crashes don't look like normal crash reports, you won't see a stack trace! Instead you'll probably just see Process = Unknown, and the crash report will contain a list of processes which were running at the time of the crash.
In this example, you can see that Biblegram was using over 25000 pages of memory. 1 page of memory is 4KB, so that's 100MB of memory, which seems much too high.
Next, fire up Instruments via Product > Profile and select the "Allocations" template. Playing around with the app, you should easily be able to locate places where the memory allocation keeps going up and up.
This "staircase" pattern is a giveaway. I'm repeatedly pushing and popping one view controller, but the memory goes up and up.
Try putting a breakpoint in the dealloc method of the problematic view controller. Most likely, this will never get hit, showing that the view controller is never released.
This is a strong indication that we have a retain cycle. When the view controller is dismissed there are still some strong references to it, so it doesn't get dealloced.
As one last verification, enter the name of the class into the search box in the top right of Instruments, and check the "# living" column. This is showing 3, when we'd expect it to show 1.
You can drill down into the instances of the view controller by tapping the small arrow to the right of the class name, and drill down further to see every place that the view controller is retained and released.
This view can be rather overwhelming: the system frameworks do a lot of retaining and releasing on your behalf! For example, instantiating a NIB can easily increase the retain count to 40 temporarily.
So: here are four common errors to look out for that may cause your retain count to be higher than expected.
1. NSTimer
If you create an NSTimer object on a view controller, be sure that invalidate is called on it when dismissing the view controller, otherwise it will retain self.
2. Observers/NSNotificationCenter
If you add an observer to NSNotificationCenter, make sure you remove all observers when dismissing the view controller, otherwise they will retain self.
3. Blocks
You should not call [self doSomething] from inside a block, this can easily lead to the block capturing a reference to self. Instead, make a weak reference to self:
BAD:
dispatch_async(queue, ^{ [self doSomething]; });
GOOD
__weak MyViewController *safeSelf = self; dispatch_async(queue, ^{ [safeSelf doSomething]; });
4. Delegates
if you use
someObj.delegate = self;
inside the view controller, check the delegate property on someObj is weak.
@property (nonatomic, weak) id delegate;
Once you've made your fixes, check that dealloc is getting hit and the allocations no longer increase endlessly.
How to send us crash reports from an iOS app
At ReignDesign, we always test our apps thoroughly before releasing them. But we're human, and occasionally apps can crash because of a combination of circumstances we didn't consider. If one of our apps crashes on your device, sometimes we'll ask if you can send us a crash report to help us diagnose the problem. Here's how to do that:
1. Sync your iOS device to iTunes on your Mac or PC.
2. Open the folder on your computer that contains crash logs for your iOS device:
On Mac OSX
a) Go to the Finder
b) From the "Go" menu choose "Go to folder..."
c) Enter ~/Library/Logs/CrashReporter/MobileDevice and click the "Go" button
d) A Finder window will open, open the sub-folder whose name matches your iOS device
On Windows XP
a) Press the "windows" key and the "e" key at the same time to open a new "Windows Explorer" window
b) In the "Address" area at the top of the window paste in %HOMEPATH%\Application Data\Apple computer\Logs\CrashReporter and hit the "ENTER" key on your keyboard.
c) Open the sub-folder whose name matches your iOS device
On Windows Vista & Windows 7 & Windows 8
a) Press the "windows" key and the "e" key at the same time to open a new "Windows Explorer" window
b) In the "Address" area at the top of the window paste in "%HOMEPATH%\AppData\Roaming\Apple computer\Logs\CrashReporter\MobileDevice" and hit the "enter" key on your keyboard.
c) Open the sub-folder whose name matches your iOS device
Now, two final steps:
3. Find the crash reports you wish to send (for example anything starting with "PigRush_")
4. Attach them to an email and send to support@reigndesign.com
How to launch Google Maps or Apple Maps from an iOS app
Today Google announced their much-anticipated Google Maps app for iOS. They also plan to make available a Google Maps SDK for iOS allowing iOS developers to integrate Google Maps in their apps, however at present API keys are only available for selected developers.
If you want to provide your app's users with the ability to open a location in Google Maps, there is an option which works today: Google have added a comgooglemaps URL scheme to their app so third-party apps can launch the Google Maps app.
Assuming you'd like to give your users a choice of opening a location in both Apple or Google maps, you can set up some code like this in a new view controller:
#import "ViewController.h" #import <MapKit/MapKit.h> @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Add a button to pop open an action sheet UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; btn.frame = CGRectMake(80,100,160,50); [btn setTitle:@"Open placemark" forState:UIControlStateNormal]; [btn addTarget:self action:@selector(openActionSheet:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btn]; } -(void)openActionSheet:(id)sender { //give the user a choice of Apple or Google Maps UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Open in Maps" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Apple Maps",@"Google Maps", nil]; [sheet showInView:self.view]; } -(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { //coordinates for the place we want to display CLLocationCoordinate2D rdOfficeLocation = CLLocationCoordinate2DMake(31.20691,121.477847); if (buttonIndex==0) { //Apple Maps, using the MKMapItem class MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:rdOfficeLocation addressDictionary:nil]; MKMapItem *item = [[MKMapItem alloc] initWithPlacemark:placemark]; item.name = @"ReignDesign Office"; [item openInMapsWithLaunchOptions:nil]; } else if (buttonIndex==1) { //Google Maps //construct a URL using the comgooglemaps schema if (![[UIApplication sharedApplication] canOpenURL:url]) { NSLog(@"Google Maps app is not installed"); //left as an exercise for the reader: open the Google Maps mobile website instead! } else { [[UIApplication sharedApplication] openURL:url]; } } } @end
Here's the app in action, example code is on Github.

For more details, see the Google Maps URL Scheme documentation.
Sharing images to Weixin/WeChat from an iOS app
Weixin (微信) is Tencent's mobile messaging product. It's highly popular in China, with hundreds of millions of users, as well as many international users who may know it by its English name WeChat. It includes both a chat feature, similar to WhatsApp, and a timeline feature similar to Path.
Tencent have a developer site in English, but the documentation is still quite sparse.

For a recent project, we needed to integrate sharing of images to Weixin.
The workflow for the user will be:
1. Create an image in the app
2. Tap a button to share to Weixin
3. The Weixin app will launch, and the user confirms they want to add the image to their "Moments".
4. The user taps a button in the Weixin app to return to our app.
STEP 1: Download and add the iOS SDK
1. Download the latest iOS SDK from the WeChat developer site. After unzipping you should have four files:

2. If you're building with the latest Xcode and targeting iPhone 5, you'll probably want to use the version of the library which supports armv7s, so copy WXApi.h, WXApiObject.h and libWeChatSDK_armv7_armv7s.a to your project folder. Rename libWeChatSDK_armv7_armv7s.a to libWeChatSDK.a.
3. Now in your XCode project go to File > Add Files and add the three files to your project.
STEP 2: Register for an app id
1. Register as a WeChat developer using the signup form. Once you've confirmed your email address, head to the My Apps page and tap "Register my apps"
2. Fill out the name of your app and other details. You can skip some optional fields like icon for now. Make sure you choose "Mobile app" as the app type, not Web app.
3. At the end of the process you will be given an app id which looks like wx123456789012
STEP 3: Integrate with the SDK
1. In your application:didFinishLaunchingWithOptions: method, add code to register your app. Be sure to replace wx123456789012 with the code you obtained earlier.
if (![WXApi registerApp:@"wx123456789012"]) { NSLog(@"Failed to register with Weixin"); }
2. After the Weixin app is launched it needs a way to re-launch your app. It does this by trying to open a URL with your app id as the protocol, for example wx123456789012://. We need to ensure we can handle these URLs, so implement these two methods:
return [WXApi handleOpenURL:url delegate:self]; } return [WXApi handleOpenURL:url delegate:self]; }
3. We need to ensure that our app delegate implements WXApiDelegate, so first add WXApiDelegate to your AppDelegate.h file:
@interface AppDelegate : UIResponder<WXApiDelegate>
and then add empty implementations of these two callbacks in the .m:
- (void) onReq:(BaseReq*)req { } - (void) onResp:(BaseResp*)resp { }
4. We also need to make a change in the Info.plist to ensure we can handle these kind of URLs. Go to your target, select the Info tab and add a new URL type as follows. The identifier can be "weixin" and the URL scheme should match your app id.

5. Now let's add a method to send an image.
- (void) sendImageContentToWeixin:(UIImage *)image { //if the Weixin app is not installed, show an error if (![WXApi isWXAppInstalled]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"The Weixin app is not installed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; return; } //create a message object WXMediaMessage *message = [WXMediaMessage message]; //set the thumbnail image. This MUST be less than 32kb, or sendReq may return NO. //we'll just use the full image resized to 100x100 pixels for now [message setThumbImage:[image resizedImage:CGSizeMake(100,100) interpolationQuality:kCGInterpolationDefault]]; //create an image object and set the image data as a JPG representation of our UIImage WXImageObject *ext = [WXImageObject object]; ext.imageData = UIImageJPEGRepresentation(image, 0.8); message.mediaObject = ext; //create a request SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init]; //this is a multimedia message, not a text message req.bText = NO; //set the message req.message = message; //set the "scene", WXSceneTimeline is for "moments". WXSceneSession allows the user to send a message to friends req.scene = WXSceneTimeline; //try to send the request if (![WXApi sendReq:req]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil]; [alert show]; } }
6. Add callback code. This will be called once control is returned to our app after returning from Weixin.
- (void) onResp:(BaseResp*)resp { if([resp isKindOfClass:[SendMessageToWXResp class]]) { NSLog(@"Response from Weixin was: %@",strMsg); } }
STEP 4: Test!
All being well, you should now be able to share an image from your code, using something like:
UIImage *test = [UIImage imageNamed:@"test.png"]; [self sendImageContentToWeixin:test];
After sharing the image, you should be returned to your app.
If you found this tutorial useful, or have any suggestions, do leave a comment!
Movember Matt
The eleventh month of the year, formerly known as November, is now Movember at ReignDesign! I've been growing out my facial hair to help raise awareness of men's health, particularly prostate and testicular cancers.
It's important to remember that 47% of testicular cancer cases occur in men under 35 years. Check out BUPA's Movember page for more facts and prevention tips.
The evidence, Day 1 and Day 30.




