That… doesn’t look right. Let’s turn on some debugging tools and see if that helps. Open the ‘Edit Scheme’ window and navigate to the Diagnostics tab. You’ll want to turn on “Enable Scribble” and “Malloc Stack”. You can read more about these methods here, but in short, “Enabled Scribble” will cause the allocator to write 0xAA to newly allocated memory and write 0x55 to deallocated memory. “Malloc Stack” will log the allocation and free history of your memory.
Let’s get our app to crash again and see if that helped.
Well, there we go. Obviously someone else is freeing self while we’re in the middle of a method. Let’s grab the PID of our crashing process. Easiest way to get this from an iOS app is to check out any log statements in the terminal.
Mosey on over to your trusty terminal and let’s see what’s happening at that memory address.
$ malloc_history 14105 0x0cdcd2d0
This is going to fill your screen with a massive spew of text. You’ll probably want to pipe the results to your text editor of choice. The important bits are right there at the top, though. Check it out:
About 100 lines of junk omitted. But there you go. We’ve got a timer that’s holding on to a button, preventing it from being freed when it should be, then all of a sudden the timer lets go and everything falls apart. Simple!
It prints a list of Rake tasks when you run Rake without a command. Not only does it help you remember what options are available in the current project, but it keeps you from accidentally performing some task if you fat-finger the rake command.
Like many people, I was thrilled when Parse announced their cloud code product. I’ve just started a little iOS project that required both persistent cloud storage and pulling data from a 3rd party API. Since the API had a great JavaScript library, but no built-in Obj-C support, moving the code onto the server had some big benefits: greatly simplified networking in iOS, allowed me to reuse the 3rd party library as is, and decreases my turnaround time should I need to modify this code in the future.
Now, I’m usually not a strict test driven developer, but these cloud code modules are a different story; the code is running on a server and accessing a 3rd party API. In this situation, quick build/test/debug cycles are impossible and testing is the only way go.
Here’s how I set up my testing environment. Please keep in mind that this is the first time I’ve used Node.js, first time I’ve written unit tests for JavaScript and the first real JS project I’ve worked on. In fact, before this, the only JS code I’d written was hackly little Safari extensions, so this is a whole new world for me. I’m writing this for someone with experience similar to mine; if you are experienced with Node, feel free to skip ahead.
Setting up the test environment
I assume you’ve already got Node and npm installed. If you don’t, they both can be installed via Homebrew.
I used Mocha.js for the testing framework and Expect.js for assertions. Mocha supports any assertion framework you can throw at it. Expect seems to work well and doesn’t generate Lint warnings like Should.js. Run the following commands from your project directory.
$ npm install mocha
$ npm install expect.js
These commands install the mocha and expect frameworks in the local node_modules directory. This greatly simplifies your environment. Code can be shared between collaborators without worrying about what framework version each dev has installed.
At this point, your Parse directory should look like this:
We’re all set to test, but first we need something to test. We’re going to add some code that just returns a helpful message. Modify main.js to look like so:
What I’ve done is load each Cloud Code function from a separate module, this worked well for me because each function is independent of all other functions, but YMMV. Let’s setup some code to test. First, create a file named message.js in your cloud directory. Now modify it to look like so.
A bit about how Node.js loads modules, since this was all new to me. When each module is loaded, there is an object created called exports that is available within that module. Any function attached to that object will be available externally when your module is loaded. So in this example, our message module creates one function called getMessage. When we call var message = require('cloud/message.js'); the object returned from the require() function is that exports object.
Creating Tests
Now let’s create some tests. First, the default directory for Mocha tests is test, so let’s put our test there. Create the test directory and put a file in there named, “messageTests.js”. Modify it to look like this:
12345678910
varmessage=require('../cloud/message.js');varexpect=require("expect.js");describe('Message',function(){describe('response',function(){it('should return the correct message',function(){expect().fail("No tests yet");});});});
First we import our message and expect modules. The describe() function is used to define the scope for associated tests. The it() function defines a Mocha test. Let’s run our test.
$ node_modules/.bin/mocha
Notice that the error message says, “Message response should return the correct message:”, so structure your describe and it messages to make that message nice and readable. Let’s replace our failing test with an actual tests.
12345678
it('should return the correct message',function(done){message.getMessage({},{success:function(message){done();expect(message).to.be.eql("Good job, buddy");}});});
There’s a few things to notice here. First, the done() function is an optional parameter to the describe() and it() methods. Any tests within will not complete successfully until the done() function is called, so you can use it to test callbacks and ensure that they were called. Second, notice the format of the expect() function. You can read the documentation for more details, but in general, the tests always follow this form, beginning with an expect() function and ending with a function.
Run the tests again and success! All our tests pass. All in all, it took me less than a day to try out different testing and exception modules, settle on Mocha and Expect, then write enough tests to nearly fully cover the Cloud Code I had written. Coming from Objective-C, the power and flexibility of JavaScript amazes me. Writing these tests was almost a joy.
I’ve been writing some Javascript using the default settings in Chocolat, tabs instead of spaces and each tab is equivalent to 2 spaces. Running most of my javascript files through JSLint is fine, but there were a few lines that were generating warnings, even though the spacing looked just fine.
if (validateCardRequestDidSucceed(stripeResponse) === false) {
response.error("Stripe card request failed with unknown error");
return; // Expected 'return' at column 17, not column 19.
}
What’s wrong here? That spacing looks just fine to me. Turns out that the default settings in JSLint want spaces instead of tabs and 4 spaces per indentation. JSLint, by default, ignores tabbed indentation, but somehow that return had been indented with spaces.
Replacing the spaces with tabs cleared up the issue.
In other news, I should probably switch to 4-space indentation. I’m not picky about spacing and, all things being equal, I might as well stick with the JSLint conventions.
I’ve been running into an issue over the past few days where [objA isKindOfClass:[ClassA class]] is returning false when clearly objA is a kind of ClassA.
I’m running these tests using SenTesting kit and I’m not compiling the .m files in my test target, which is the only issue that StackOverflow suggests.
I am including my Storyboards in my testing target. Perhaps that’s the problem? Let me just remove those Storyboards from the testing target…
BOOM. That was it.
Also, for future reference, in case anyone finds their way here while looking for how to load storyboards in a SenTestingKit test target, here’s how:
Sometimes I long for the day when I get to create an iOS app that just uses Apple’s default interface element. Of course, this doesn’t last long, because using and abusing UIView is fun. Over the years I’ve picked up a few tips and tricks for making the most out of your time. The best tip is, first and foremost, you need to start copying Apple.
This cannot be emphasized enough. Apple’s framework developers aren’t perfect and they have made mistakes, but overall they provide excellent frameworks, especially for UI development. Make your class interfaces look like Apple’s class interfaces. Try to subclass Apple’s own elements before going off and creating your own. Don’t reinvent the wheel.
That being said, any iOS app of a decent size will create many custom UIView subclasses and learning how to properly subclassing UIView will reap benefits.
You’ll get a lot of useful behavior right out of the box.
You increase readability of your code and make it easier for future developers to understand what you’ve written.
Here are some tips for abusing UIView
Subclass the right class
If you are creating a generic control, subclass UIControl. If you are creating a custom button, subclass UIButton (or just create a custom button! That’s usually all you need). If you are creating a custom switch, subclass UISwitch (lols, just kidding. UISwitch is a terrible and fragile class to subclass. Write your own switch if you need something custom).
I see so many developers implementing complex touch event listeners in their UIView subclasses or a needless delegate protocol when they could have just gotten the same behavior for free by using the proper superclass.
Use UIViewAutoResizingMask
Your first attempt at custom layouts should always use UIViewAutoResizingMask (this changes in iOS 6.0, read more on developer.apple.com). Setting these up takes a trivial amount of time and you stand a pretty good chance of eliminating your custom layout code. Writing flexible and extensible layout code is very hard, which is why most developers don’t bother and just hard-code a bunch of magic numbers into their view layouts. Your layout may always be 320px wide today, but someday you’re going to enable landscape orientation in your app and having to go back in and debug your layout all over again is going to be a major headache.
Override layoutSubviews
Realistically speaking, you’re probably going to have layouts that springs and struts can’t handle. If you need to do custom layouts, do them in the correct location, by overriding layoutSubviews. You should always put your layout code in this method. Here’s some great reasons why you should be doing this.
layoutSubviews will only be called once per run-loop. You can call [self setNeedsLayout] as much as you want without worrying about taking a performance hit laying out your views needlessly.
layoutSubviews is common knowledge. Other developers (and yourself in 6 months) should know to look here for layout code. No need to try and scan unfamiliar code to find the method doing layout; it’s always the same one.
Putting all your layout in one method makes handling state changes much more robust. Big Nerd Ranch has a writeup you should read.
It’s fairly common to have your layout depend on the properties of your subviews. This is how people tend to handle layout and it’s wrong.
123456789101112
-(void)setDeleteButtonVisible:(BOOL)visible{if(visible==_visible)return;_visible=visible;if(visible){// move some stuff around to make room for this button}else{// move stuff around to cover the empty space// where the delete button was}}
The biggest issue with doing this is that it scatters your layout code all over your class. Once you get two, three, four or more properties that influence your layout, each property setter becomes an incomprehensible mess of layout code. Don’t do this. A much better way to handle property-based layouts is to override layoutSubviews.
12345678910111213141516
-(void)setDeleteButtonHidden:(BOOL)hidden{if(hidden==self.deleteButton.hidden)return;self.deleteButton.hidden=hidden;[selfsetNeedsLayout];}-(void)layoutSubviews{[superlayoutSubviews];if(self.deleteButton.hidden){// layout for hidden delete button}else{// layout for visible delete button}}
You can feel free to call [self setNeedsLayout] as much as you want, those calls will be consolidated and the layout methods will only be called once per run loop. For complex layouts, this can be a massive performance win.
Override sizeThatFits:
- (CGSize)sizeThatFits:(CGSize)size is the unsung hero of custom UIView subclasses. This method can be used to set minimum sizes, maximum sizes, and optimal sizes. The trick here is that the UIView method sizeToFit calls through to sizeThatFits: with the current size, then resizes the view based on the response. sizeToFit: is always the method that you should override, it’s the designated initializer of sizing methods. A great use for this method is to allow users to initialize your class with a zero sized rect while still maintaining a proper frame.
Now, if someone really wants to initialize your view to an absurd size you can prevent this by overriding setFrame:, but in my experience, when someone resizes something to the wrong size, it’s obvious what they did wrong. When they’re attempting to resize something and it just won’t become the correct size, it’s usually a mystery why. Don’t surprise your users, let them shoot themselves in the foot, but make it obvious that they are shooting themselves in the foot.
Respond intelligently to weird frame sizes
If your UIView is instantiated by calling init, the default implementation will call through to initWithFrame: and pass CGRectZero. This is very common, and it shouldn’t cause your view to blow up or completely break. If you have a minimum size that your control should be, resize yourself in initWithFrame. If you don’t have a minimum size, make sure your subviews are pinned to the correct edges of your bounding rect so that they behave correctly when your view is resized. These two views should both have the same frame and be layed out identically:
1234
CGRectframe;// Declared to be something reasonableMyCustomView*view1=[[MyCustomViewalloc]initWithFrame:frame];MyCustomView*view2=[[MyCustomViewalloc]init];view2.frame=frame;
A UIView that blows up when instantied with a size zero frame is a perpetual source of developer annoyance. Don’t do this. If you need to use default frame sizes, provide an initializer that doesn’t take a frame as a parameter, and override initWithFrame: to ignore the input frame size. Make a note in the documentation to this effect.
Override pointInside:withEvent:
The default behavior of pointInside:withEvent: returns YES if the point is within your bounds. Override this method if your shape does not completely fill its bounds. For example, if you have a button with a transparent center region, you may not want to respond to taps in that region. Override this method to return NO for any points within that transparent area.
Even more useful, if you have a control that is smaller than the Apple HIG recommended guidelines of 44x44px, you can respond to touches outside your bounds, effectively increasing the tap target for a given button.
Don’t override drawRect:
Overriding drawRect: causes a performance hit. I haven’t profiled it, so I don’t know if it’s a signifigant performance under normal circumstances (it’s probably not), but in most cases, folks who override drawRect: can accomplish what they want much easier by setting properties on a view’s layer property. If you need to draw an outline around a view, here’s how you would do it:
Learning how to properly subclass UIView will save you a lot of coding, a lot of debugging and will make it much easier for future maintainers of your code to read and understand what you’ve done, arguably the most important consideration for a developer.
This is my million dollar idea. The idea is called “Sensational.ist”. Install an extension in your browser. Whenever you read a news article that is full of sensationalist nonsense, trigger the extension. If enough people have labeled an article as sensationalist, all new visiters will see a warning page.
Caution: This article is complete bullshit.
This article was likely written with a goal of being confrontational to drum up pageviews and advertising dollars. By visiting this site you are supporting the fucks that are ruining online journalism. Please don’t visit this page. Rest assured that whatever meager content that was there is utter nonsense and by avoiding it you are helping to get that ass goblin fired.
Big view controllers in big projects tend to accumulate a lot of private methods and properties. In a perfect world, these methods and properties should be carefully organized into functional groups and carefully documented. In the world we actually live in, that shit doesn’t happen, which is why I’ve resigned myself to organizing everything alphabetically.
To make my life easier, I created an automator service that sorts everything for me. Here’s how you create it yourself:
Open Automator.app
Create a new workflow and select “Service”
Drag the “Run Shell Script” workflow into the workflow pane.
Above the workflow, change the drop downs to read “Service recives selected text in Xcode” and check the “Output replaces selected text” box.
Save the service with an appropriate name and you’re done!
Keep in mind that any comments need to be inline and all method names need to be on one line, no splitting accross multiple lines. I’m not too concerned about this, as it fits my style (I have word wrap turned on) and since nobody ever reads comments on declarations in the .m file anyway. When I get a chance I’d like to update this to clean up property declarations (all the names at the same tab-stop) and remove extraneous spacing in method declarations.
A few months ago Matt Gemmell created a fantastic writeup on creating open-source components. One salient point he missed, though, is that you must compile and test your code with the strictest warnings available. You never know who’s going to be using your code and what warnings they have enabled. Assume the worst, and turn on nearly every warning you can in your project. Peter Hosey’s list is a great start (there’s even some AppleScript to automate turning on all these warnings). If you’d like to be extra cautious, use the -Weverything flag in Clang to turn on all the warnings.
I exclusively use Apple’s iMessage for chat. Most of my coworkers use Adium. Ever since I started this job there have been weird issues were coworkers can’t see me online and don’t respond when I message them. I’ve confirmed that they are not actually getting the messages (and they aren’t quietly hellbanning me).
Also, the name of my lapop is the Emoji characters 🐒💨.
Also, your default location in iMessage is the name of your computer.
Turns out there’s a bug in either iMessage, Google Chat or Adium (probably Adium, since iMessage <-> Google Chat works just fine) where Emoji characters in your location cause you to not be visible in Adium. I changed my location to something more vanilla and now all my coworkers can see me online. Hooray!