Memory leak detection tools - iphone

Does Apple's Xcode development environment provide any tools for memory leak detection?
I am especially interested in tools that apply to the iPhone SDK. Currently my favourite platform for hobby programming projects
Documentations/tutorials for said tools would be very helpful.

There is one specifically called Leaks and like a previous poster said, the easiest way to run it is straight from Xcode:
run -> Start with Performance Tool -> Leaks
It seems very good at detecting memory leaks, and was easy for a Non-C Head like me to figure out.

Select Profile from the Product menu in Xcode 6 to launch Apple's Instruments tool. (The application is located inside the Xcode application's package contents: /Applications/Xcode.app/Contents/Applications/)
A commercial alternative is OmniObjectMeter. (Discontinued by The Omni Group)

The Clang Static Analyser is great for finding bugs in C, C++ and Objective-C code:

Here is the link for using instrument from xcode to detect memory leak/performance of you ios/mac application
Steps to run instrument from Xcode

You can run the tools within Xcode over menu -> run -> start with performance tool -> ...

Does Apple's Xcode development environment provide any tools for memory leak detection?
I am especially interested in tools that apply to the iPhone SDK.
Yes. Apple calls them "Instruments" (there's more than just memory tools).
See Apple's Introduction to Instruments User Guide. In particular, see Locating Memory Issues in Your App. It provides examples of how to use the memory-oriented trace templates.

ObjectAlloc and MallocDebug should both be of help to you. If you installed the entire SDK, they will be found in Developer->Applications->Performance Tools.
Their names give you a pretty good clue as to their functions, OA, tracks the objects create and MA is a general memory leak tool.
I haven't tried them with iPhone development yet, but I have to believe that they would work there as well.
Assuming you have registered for ADC iPhone developer site, here the link to follow:Instruments User Guide

When using rustyshelf's solution make sure you test on the iPhone and not on the simulator. Memory usage is dramatically different.

Made a sum up of the main memory leak tools: iphone-essential-performance-tools-list

Step 1. Pick the Allocations instrument
Choose the profiling template for Allocations:
On the main Instruments interface, click VM Tracker, if present, and press the Delete key since you won't be needing that particular instrument:
By clicking the plus button in the top right, you can add more instruments for different kinds of testing, but I won't be covering them in this tutorial.
Step 2. Set up your Instruments settings
Before running any analysis, there are a few things you need to do. First, you need to plug in an iOS device that has your app installed on it. It must be a physical device because the iOS Simulator is still a simulator and may not accurately represent memory use in your app or how an app might perform under memory pressure.
To pick your target, click My Computer near the top, hover over your device, and then pick your app from the sub-menu:
Next, there is a panel where you can alter the settings for the types of allocations you will be viewing. Besides making sure the Created & Persistent bubble is checked, there is not much you need to do beforehand.
Step 3. Press record to run the instrument
Once you press the Record button in the top left, your app will start up on your device, and Instruments will begin to chart your allocations. All you need to do here is run through your app, focusing on possible problem areas to see if more memory allocates than deallocates. This could mean doing a lot of repetitive tasks, but you'll thank yourself later.
You should see something like this:
I recommend running through your app once and getting to a stable point in memory so you have a good baseline that will make any increase noticeable. When you are satisfied you have enough data to test, press the stop button in the top left.
Step 4. Analyze
The first thing I do is set my inspection range to measure the total persistent bytes at my baseline. That persistent byte number is located right under the allocation summary.
To actually set the inspection range, use the keyboard shortcut Command < for the left inspection range and Command > for the right inspection range. In our app, we have a baseline of about 20MB.
Then, I move my right inspection range to a point where I had run through the app again and came back to our root. Here, you can see memory is about the same. So, by doing this a few more times and seeing your memory come back to our baseline, you can assume there are no major memory issues.
There are different ways to analyze this data that I won't cover here, but be aware that there's a whole drop-down menu of ways to view and analyze your data.
Step 5. Marking generations
If you prefer not to deal with the inspection ranges as much, there is a feature called Mark Generation. There is a button for it on the right panel of instruments.
This button will mark points on the timeline of instruments based on where the inspection line is. It does this in order to keep track of all the allocations since the previous mark, or from the beginning if there are no other marks. You can mark generations as you are running the allocations instrument or after you have stopped the run, as in this example:
Step 6. Check out the stack trace
The last thing to cover is looking at the stack trace. For this, you want to set your inspection range to highlight all the allocations, and then look at the statistics view, making sure the Created & Persistent bubble is selected on the right panel. In the statistics view, make sure Persistent Bytes is sorted from highest to lowest. There are a lot of allocations here, and it can be hard to understand what is going on, since a lot of them are system allocations.
Going deep
Look at the largest allocations and click on the right-facing arrow. A lot of times there will be allocations inside the ones you clicked on and many of them won't have meaning to you.
As you highlight different allocations after clicking an arrow, continue looking at the extended detail on the right panel. Eventually you will come across some bold text that leads to actual code in your project, telling you what the issue might be.
If you double-click one of the bold items in the stack trace, it will take you to the actual code (assuming you ran allocations on an app you own).
There are a lot of useful things about this view, one being the mostly yellow tags on the right showing you just how much memory each method call is taking up. Every app is different so you, the developer, have to decide if the highlighted method is a problem, something you can optimize, or just an unavoidable part of your app.
In my case, that UIColor variable is something that is persistent and used throughout our app and is therefore, acceptable throughout the life of our app.
found here

Try this one also, a simple tutorial to start with Xcode insturments
Memory leak tool: http://www.raywenderlich.com/2696/
Basic: http://www.raywenderlich.com/23037/how-to-use-instruments-in-xcode

Related

Xcode: compiled application file does not work as in debug runtime

I have an issue where when I run my application in debug mode, the application shows obvious runtime lags. As specified in numerous articles, the application bundle will run up to 10X faster than when running from xcode (including with instruments).
However, when I open the app (going through the project explorer/products/app_name.app) and show in finder then run the app, several features that work perfectly in debug mode (in my case, certain keyboard press functions).
The app runs much faster as expected than the debug mode runtime, but lacks some of the behaviors which work in debug mode. Furthermore, some other actions close the application altogether.
I don't know where to start figuring this out but have some intuition and would like confirmation what it might be:
1-Instruments: is there a difference of memory usage between debug and application bundle for which debug keeps a cap on memory usage, CPU usage etc?
2- COnsidering cache misses, is it possible that my nSResponder when I activate a key does not catch some later down the track switch cases, which will create a cache miss? (I doubt this since my controls file runs as an extension to one of my main loops). Note: If this works fine in debug mode, why would it not work in the application itself?
Any pointer to why this behavior greatly appreciated, so that I don't make large changes that won't affect the outcome (It's a large project).
So are you saying that when you compile for debugging (-ONone), then things work. But when you compile for release then some things don't work?
Try unchecking 'Enable backtrace recording' in the Options tab of the Run scheme action.

XCode 4 - IPhone Dev - Good Debug Tutorial

I'm beginning IPhone development with XCode 4 and Objectiv-C. Since I think strong debug and IDE knowledge is required to master a language, I'm looking for good resources about the debugging process and XCode.
A problem I faced recently was that, an unknownException was being thrown in a sample code and I couldn't know how to debug it, since it crashed right after jumping into my Main. I think with a better configuration, it would have been much easier to debug !
I've already found this resource : https://developer.apple.com/library/ios/navigation/
But I couldn't find something related to debug in there... Did I miss something ?
Andy, this first is about super basic debugging: http://mobile.tutsplus.com/tutorials/iphone/xcode-debugging_iphone-sdk/
And here you can find two excellent tutorials:
http://www.raywenderlich.com/10209/my-app-crashed-now-what-part-1
http://www.raywenderlich.com/10505/my-app-crashed-now-what-part-2
Easy to make mistakes in Objective-C...
Not having a view attached to your view controller
Sending a message to a deallocated instance. Turn on NSZombieEnabled.
Forgot to add the Framework (e.g. MapKit)
If the crash isn't fixed at this point. Set a breakpoint in your app delegate and just step through every line until it crashes. Move the breakpoint up, run again, and inspect the values.
Apple has a list of what they consider to be the best debugging tricks for iOS here.
There is also a couple of videos on the developer's site. I can never find out how to make a direct link, but there aren't that many videos, so just search for "debug":
https://developer.apple.com/videos/wwdc/2012/
There is also one from last year:
https://developer.apple.com/videos/wwdc/2011/
Access to the developer site requires registration.
Should you ever consider venturing into OS X territory, then here is the Apple-approved debugging magic.

how do I debug a distribution build

Ok
SO recently I've being having a lot of trouble with an application working in debug mode but not working in distribution mode.
Is it possible to use xcode debugging tools such as break points and variable tracing with an adhoc distribution build of an app?
If it's not how would one usually go about debugging such a thing?
Assuming that your crash logs aren't giving you any clues (you'll need to hook up to the device to get them) there are lots of things you can do.
But I'd start by looking at the crash logs ... the clues will be there and don't forget Apple make distribution crash logs available to you through iTunesConnect.
1) Copious logging is one thing. Lots of developers use a switch so that in debug, logs go to the console but for other builds they are dropped. Consider a different option where you log to a file instead. You could then push the log files to a remote server for debugging. It's a bit of a slog to set this all up, but once you've done it, you'll wonder how you ever lived without it.
2) Another option is to use Flurry and log events when you detect that things have gone wrong. This can cover more controlled problems when things aren't as expected rather than random crashes. This can be a useful feature for released apps provided your terms and conditions are clear about what data you are logging and why.
3) Make sure you do a clean build, I'm sure you've already done this, but sometimes it clears these issues.
4) Are you using external libraries / modules? I've come across issues with older versions of TT where the arm6/7 build settings were wrong and this was causing issues for distribution builds. Basically check through the build settings for each profile and make sure it is what you expect.
5) Suspect a race condition. In distribution mode (often because the logging is turned off) you will find that your application runs a little bit faster. That can reveal timing issue bugs in badly written code.
So yes ... there is a lot you can do ... you just can't attach the debugger ;-)
Not possible to debug an application in distribution mode.
The build configuration difference between Distribution, Debug, and Release is really whatever parameters you have set for that in XCode. If your Distribution config is giving you problems and the release isn't, the easiest way to fix it is to go back through Apple's steps on copying the Release config and making the changes to make it a Distribution config, like you did originally.
The alternative is to go through every line of the configurations for Release and Distribution and find what's different. The other way is a LOT faster. :)

Xcode 4 Tips and Tricks for Xcode 3 users [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
As most of you have probably seen, Xcode 4 has been released officially today. Now I know that plenty of devs out there have been using the preview versions, and it'd be great if people could post any great tips, tricks, or keyboard shortcuts they've learned using those version now they're no longer under NDA. This could be especially useful for those upgrading from Xcode 3 (like me, downloading right now).
Note: Apple have released a 'transition guide' that has plenty of stuff in about getting from version 3 to version 4, but I bet there are loads of great tricks people out there have learned that aren't in there.
I liked reading this Blog: Pilky.me - Xcode 4: the super mega awesome review.
It presents a good comparison, I especially liked his conclusion near the end.
Currently I have only one tip for Xcode 3 users - don't use xcode 4 unless you have free time to start learning again and/or are willing to report lots of bugs. Wait at least until 4.1. There are still lots of bugs unresolved. Nothing is stable. Also Xcode 4 advertises as having single window ui which is nice, but is unstable as U238. Also - it's probably single thing that is good about new Xcode 4. So here are some of my headaches currently:
There is no possibility to commit whole project (except for separately selected modified files);
There is no possibility to push (if SMC is git). At least I haven't found that;
Since symbol indexing is broken you cannot:
see normal syntax highlight;
jump to certain symbol definitions;
Jump bar is just one big misunderstanding:
Previously comfortable Ctrl+2 shortcut from Xcode 3 which lists method names and pragma marks has now become finger breaking Ctrl+6 (emacs user's rejoice</flamewar>).
There is no direct button to switch between interface and implementation files.
If you have 13.3" macbook[pro] - don't even try to use navigators with utilities (inspectors or libraries).
Also transition guide is made for working Xcode 4 which it is far from.
Update 1:
There is no such thing as "Build & Run". Only build, build for running, build for testing, build for profiling, build for archiving. Then just run without building and run without profiling. AFAIK it supposed to be easier so summa summarum - 8 actions instead of 1. Go figure.
So these are only few of my instantly found glitches for Xcode 4.
P.S. probably will be updating this in upcoming few days.
#Ohmu: The 3-finger up/down trackpad/magic mouse swipe gesture for switching between header (.h) and implementation (.m) files still works a treat.
XCode 4 has a lot of awesome new features. I'd recommend starting to adjust to it by watching last year's WWDC2010 videos - they dedicated a lot of time to going through some of the new stuff.
I love the new assistant mode - it makes it really easy to navigate through your interface/implementation files. This mode also allows you to create your user interfaces alongside your controller classes, which makes development both easier and more effective than doing it in two completely separate programs!
The jump bar (found along the top of your source code) is a really fast way to leap about your project, making it really easy to get exactly to the place in your code that you're interested in.
The version control viewer makes it really easy to track changes. I now use SVN for all my projects, even the ones I work on alone because it really makes it clear to see how the project has evolved over time.
There are settings to set how your layout changes and what's displayed when you build, when you run, when you end a run etc. etc. which I'm also finding really useful because you want to see different things when you'e debugging to when you're back in your code. It's really nice that Xcode helps you easily arrange your layout to exactly how you want for different scenarios.
The code templates (which can be found in the toggleable right-hand-side toolbar) are also really useful, and you can create your own in order to quickly get code you often write down.
Some more subtle things that I've grown to like:
The 'Fix It' feature works really well for quickly replacing typos. I find I don't even have to read the correction Fix It will make because the fix is so natural.
Control-I short cut for re-indenting code. This is really useful if you add a new pair of braces round your code and you want to quickly reformat. I don't think there was a nice shortcut for this in Xcode 3.
Hitting the escape key to bring up autocomplete suggestions seems to bring up much more helpful suggestions in C++, and looks a lot more beautiful all round!
On reliability, I've been using a combination of Xcode 4 and Xcode 3 since Xcode 4 first entered beta. Whenever Xcode 4 packed in for me or wouldn't let me continue with what I wanted to do then I'd just switch over to Xcode 3 as the two are completely compatible. What I got was a really nice transition period and now I'm completly using the latest build (first week of March) so I think it's very stable.
For people that don't like change, this update is going to be hard. It'll be particularly challenging as a lot of the keyboard shortcuts have changed to make new for a lot of new features. The most obvious difference that people are going to oppose is the new all-in-one window layout. I'm sure people will get used to it over time and realize that this way of viewing everything to do with your project is much more effective both in real estate and in navigation terms.
Enjoy using Xcode 4, it really is an amazing improvement over the last version, and it continues to add to the awesome time I'm having writing Mac and iOS applications. :D
More shortcuts than you can shake a stick at here:
http://cocoasamurai.blogspot.com/2011/03/xcode-4-keyboard-shortcuts-now.html
However, completeness is obscuring clarity. For example, I can't straightaway see the shortcut for toggling between a header file and its associated method file. so I recommend one shortcut per answer, and the votes will filter out the best ones.
If you need to open plist files when you are not coding you should keep a copy of XCode3/Applications/Utilities/Property List Editor.
Property List Editor opens within the blink of an eye. But XCode4 takes minutes until it finally shows the plist file.
I guess Apple wants me to replace my 2008 MBPro
NB: Apple's official transition guide has moved/been updated (they didn't update the URL, sigh). It's now at:
http://developer.apple.com/library/mac/documentation/IDEs/Conceptual/Xcode4TransitionGuide/Xcode4TransitionGuide.pdf
The only way for me to like XCode4 is thinking it as a different product.
There's NO evolution over XCode3, just lots of drawbacks for the way I use it.
Who changes (almost all) shortcuts between version of the same software?
Why do I have to learn back from zero how to use and configure my projects? Sounds like punishment, not evolution.
How good is XCode4 for multiple monitors usage? It was clearly designed for a single monitor user, but unlike Xcode3, its UI cannot be as easily (and persistently) changed.
Although it can be disabled (and must), auto code check for errors... So we're back on VB6 now?
I'm a BIG Apple fan, though XCode4 falls short on developer satisfaction due to its lack of customization (compared to XCode3).
Not using XCode3 as a comparison, it is indeed a good IDE.
A frustrated developer,
Cheers.
Risky business: Moving to Xcode 4 will introduce you to a whole new level of strange behaviour, bugs, and pain. E.g. having third-party frameworks (like Three20) in your app, means that you won't be able to build a proper archive, without jumping through various levels of hoops. Don't move to Xcode 4 yet, if you can. If you do, there are some tips below.
Keep your archives safe: ...prior to installing Xcode 4 (from 3). You will lose them (most likely) and with them lose your ability to symbolicate your crash logs.
Adding frameworks: It took me a while to figure this out, and it's nowhere in the docs. You cannot simply do this by right-clicking on the project or a group (like in Xcode 3). You need to go to the project view, select your target and go to "Build Phases" tab. Frameworks can be managed under the "Link Binary with Libraries" section.
Setting target dependencies: Similar to the above, in the "Target Dependencies" section of the "Build Phases" tab.
Delete action-BEWARE: "Delete" (instead of "Remove Reference Only") directly erases the file from your drive. It doesn't go into the Trash, so you cannot recover it.
Text Editor: Here a couple of good ones:
Cmd-clicking on a class name will take you to the implementation (or header) file of that class, cmd-clicking on an object will take you to where the object is declared.
Alt-clicking will open a documenation popup for the object you clicked on.
3-finger sideways gesture to left is the Back button, and goes to your previous file. Gesture to right goes to your next file in the stack. (not sure if this was true in XCode3)
http://pragmaticstudio.com/screencast-tags/xcode4
After watching these great little videos, I instantly warmed to XCode4
They have really sorted it out big-time in so many different places, making conceptual changes such as:
one window = NICE
TextWrap
removed annoying 'stop running + rerun' dialog
good color scheme facility
CMD SHIFT O to locate a header file
The auto completion is sorted out beautifully
clear console button
search & replace NICE
new keybindings NICE
On-the-fly error checking - love it!
As you can see, I made notes over the first 2 days of using it; every time I liked something, or every time something went wrong I would jot it down.
So far I have listed 16 problems, but these are all glitches, such as the colouring system going wrong in certain situations etc... ie all minor things that will get patched up pretty soon in updates.
With the occasional crash, I am not going back to 3.x unless I absolutely have to.
The only thing which really gets my goat is that Apple STILL refuse to support incremental updates. it is totally crazy, and I hope everyone makes a lot of noise about it until they sort it out.
I wondered where per-file compiler flags had gotten to.
Spoiler: Select project, select target, select Build Phases tab, expand Compile Sources phase and rejoice.

iPhone compile for thumb

I've heard it might be a good idea to turn off "compile for thumb" in an iPhone target's settings to increase performance. I'm having some trouble finding this setting though. Since I couldn't find it in my current project, I decided to make a new one (where I could find and set it), and copy my files over to it (and also update all libs I'm using at the same time).
But now it seems like this setting has disapperad from this new project also. No matter what SDK I choose, simulator or device, the setting will not show up in the target settings! I do seem however to still have a variable called GCC_THUMB_SUPPORT under the category "User-defined" all of the sudden. What is this?
I tried making a new target, but the setting will not show up in that either (not even GCC_THUMB_SUPPORT).
GCC_THUMB_SUPPORT is the right variable. Just set it to NO to disable THUMB code generation.
A general rule of THUMB is, to disable it if your code is floating point heavy :)
More about that here.
Update:
The advice to compile for the THUMB instruction set is no longer valid (actually since the iPhone 3GS).
I've found that the compiler settings ("GCC 4.2 - Code Generation", "GCC 4.2 - Language", etc) only show up in the Target info build settings window when the Active SDK is set to Device -- and the "User-defined" category only shows up when the Active SDK is Simulator.
And yes, disabling Thumb compilation can be a big help to performance if you're dealing with lots of floating point math (e.g. floating-point audio processing). Though it's not, of course, an all-purpose magical speed-up (and supposedly Thumb-compiled code can run faster in some situations), so you'll probably only find disabling Thumb useful if your code has that kind of bottleneck.
"Compile for Thumb" should be under Target/Get Info/GCC 4.2 - Code Generation. If it's not there (I'd be surprised if it's not), set the user-defined variable.
Keep in mind that this improves performance only under a narrow set of circumstances that you should understand before fiddling with it.
The standard instruction set for ARM is 4-bytes. Using "Compile for Thumb", the compiler is able to use 2-byte instructions. This results in a much smaller library, but also a slower one (somewhat debatable). More critically, there are issues with running under ARMv6. In our case, we could not generate stable output from Monotouch (fix in MT4.0 alpha). In Xcode, you can find the setting by clicking on your Target, and looking under Build and searching for "thumb". Mine is under GCC 4.2 - Code Generation, but sometimes it is under LVVM GCC 4.2.