2015-03-01T21:57:36-08:00http://jimkubicek.com/Octopress2015-02-16T14:14:00-08:00http://jimkubicek.com/blog/2015/02/16/creating-a-swift-collectionLet’s say you’d like to create your own collection class. In this example, it’s going to be a collection of books that only allow the addition of a new book if it’s written by a select list of your favorite authors.

So good so far. Now we need to add some accessors. It would be nice to know how many books are in the collection. Indexed access to the books would be great. The ability to iterate over our books in a for x in y block would be fantastic. Let’s go about adding that behavior.

In order to enable using our collection in a for loop, we’ve got to adopt the CollectionType protocol. Let’s add that to our MyCollection declaration.

Well then. That looks simple, except what is Self.Index and Self.Generator.Element? Let’s read the definition of _CollectionType and SequenceType.

12345678910111213141516171819202122232425262728293031323334

protocol_CollectionType:_SequenceType{/// A type that represents a valid position in the collection.////// Valid indices consist of the position of every element and a/// "past the end" position that's not valid for use as a subscript.typealiasIndex:ForwardIndexType/// The position of the first element in a non-empty collection.////// Identical to `endIndex` in an empty collection.varstartIndex:Index{get}/// The collection's "past the end" position.////// `endIndex` is not a valid argument to `subscript`, and is always/// reachable from `startIndex` by zero or more applications of/// `successor()`.varendIndex:Index{get}typealias_Elementsubscript(_i:Index)->_Element{get}}protocolSequenceType:_Sequence_Type{/// A type that provides the *sequence*\ 's iteration interface and/// encapsulates its iteration state.typealiasGenerator:GeneratorType/// Return a *generator* over the elements of this *sequence*.////// Complexity: O(1)funcgenerate()->Generator}

Informative. Now we need to know what _SequenceType, ForwardIndexType_Sequence_Type, and GeneratorType do.

1234567891011121314151617181920212223242526272829303132333435

protocol_SequenceType{}protocolForwardIndexType:_ForwardIndexType{}protocol_Sequence_Type:_SequenceType{/// A type whose instances can produce the elements of this/// sequence, in order.typealiasGenerator:GeneratorType/// Return a *generator* over the elements of this *sequence*. The/// *generator*\ 's next element is the first element of the/// sequence.////// Complexity: O(1)funcgenerate()->Generator}protocolGeneratorType{/// The type of element generated by `self`.typealiasElement/// Advance to the next element and return it, or `nil` if no next/// element exists.////// Requires: `next()` has not been applied to a copy of `self`/// since the copy was made, and no preceding call to `self.next()`/// has returned `nil`. Specific implementations of this protocol/// are encouraged to respond to violations of this requirement by/// calling `preconditionFailure("...")`.mutatingfuncnext()->Element?}

Whew. I think we’ve exhausted that rabbit hole. Now we can start building up our collection class. First, let’s create a book generator. Since the specifics of this type only need to be known to MyCollection, we’re free to create it as a private inner struct.

This is a bit of trickery. The GeneratorOf<Book> type is a type-erasing generator. GeneratorOf is a GeneratorType that takes a Generator on initialization. Using GeneratorOf as our generator type allows us to declare a public generate() method that returns a known type (GeneratorOf) without exposing to the world the actualGenerator type we’re using.

]]>2015-02-14T21:13:00-08:00http://jimkubicek.com/blog/2015/02/14/creating-a-homebrew-formula-for-a-python-projectI just finished writing a homebrew formula for a python script I wrote, I’m going to walk through how I did it. Hopefully this helps anyone else who is thinking about distributing their code.

Why did I use Homebrew and not Pip? Two reasons: first, my code requires some Java .jar files. The front end is python, but a big chuck of the code is Java, so I didn’t have any particular allegiance to Pip. Second, I think Homebrew is the most common package distribution method on OS X. Not everyone will have Pip installed, but anyone who can use my script, will have Homebrew installed (It is the easiest way to install Keybase, which I require).

As an example, I’m going to write a Formula to install my python script Switters.

First, you should push your package to Github. This will give you both a place to host your downloads and a homepage URL that you will need to add to your Formula. Homebrew requires that you version your project, so make sure your commit is tagged with a version.

You’ll need to find the download link for your repo. Checkout the Releases page on github for the download URL. It should look something like https://github.com/jkubicek/Switters/archive/0.1.2.tar.gz.

Now, run the command to create your formula.

1

brewcreatehttps://github.com/jkubicek/Switters/archive/0.1.1.tar.gz

This creates a formula at $HOMEBREW_REPOSITORY/Library/Formula/switters.rb and opens it in your text editor. If you get a warning, “Version cannot be determined from URL”, add the correct version to the formula with version '0.1.1'. You’ll also need to add your homepage. It’s fine to use the project’s Github page here.

Homebrew recomends that you explicitly add your python dependancies. For dependancies hosted on PyPI that means you’ll need to browse PyPI to find the download URL for your resource. Here’s an example resource entry for Tweetpony:

Now you’ll need to check the build system. Don’t bother with Homebrew’s interactive installation. It doesn’t run your install method, so it doesn’t let you debug the installation steps. Instead, run a regular install command with a few helpful flags. The results of the --verbose flag are obvious. The --debug flag will stop the installation on errors and give you an interactive prompt. From here you may print a stack trace or open up an IRB session. Very helpful.

1

brewinstall--verbose--debugswitters

Take note of the SHA that Homebrew reports, you should add this to your Formula.

If everything goes well, the script should have run successfully and… nothing should have been installed. You’ve got to add the installation method.

First, let me explain the structure of my Switters project. I’ve got an executable at the top level of my project. There are two local python modules, switterslib and zxing and two Java .jars located in zxing_java. In order for everything to work, I’ve got to make sure my imports from PyPI are installed correctly and that the local resources are put in the correct spot. First, lets get our remote resources setup.

What does this do? First, we append HOMEBREW_PREFIX+"Cellar"+name+version+"libexec/vendor/lib/python2.7/site-packages onto the PYTHONPATH environment variable. This ensures that Python will be aware of this directory and look here for the necessary modules. We’ll see how that works in a bit. Next, we iterate through our resources, create a stage environment, and call a special Homebrew python command that installs our dependancies into libexec/vendor. After installation, the actual location of these libraries will be libexec/vendor/lib/python2.7/site-packages, hence the environment variable we set as our first step.

Here, we append the raw libexec path onto PYTHONPATH and copy the switterslib, zxing and zxing_java directories into it. This ensures that when our formula is installed, our python script can find these packages.

Finally, we install our script into the bin directory and run the env_script_all_files command on everything in the bin directory. This creates a shell script that sets up our python environment (hence having to add specific directories into PYTHONPATH) and calls each script in the bin directory. This script is located in the HOMEBREW_PREFIX+"Cellar"+name+version+"/bin" dir. Everything in this directory is then symlinked into /usr/local/bin/ which is (hopefully) in your PATH and now you’ll be able to call the script from anywhere!

]]>2013-11-02T21:51:00-07:00http://jimkubicek.com/blog/2013/11/02/im-learning-android-devIt’s about time I took a look and saw how the other half lived. I’m learning Android development. I bought the BNR Android book and have started working my way through the chapters. Keeping in mind I’ve only been doing this for two or three days, here are my thoughts:

Big Nerd Ranch writes exceptional books.

The Android Emulator is slow. It’s like DMV slow.

I’ve spent a surprising amount of time cleaning builds and restarting Eclipse and the emulator. I wouldn’t expect to get into that kind of debugging so quickly, especially on such a simple project. And while I’m complaining about Eclipse, non of their image assets are Retina. Since this is the only non-retina app I’ve used in a while, the appearance is strikingly bad.

String handling in Android is much better than in iOS. Has anyone written anything similar for iOS? Checking the googles…

I haven’t used Java since 2006 or 2007. It was surprisingly easy to pick back up.

I realize that my complaints about Eclipse and the emulator can be fixed by switching to a different IDE and using alternate emulators, but I’m making a conscious effort to learn the official way to develop Android apps before I strike out on my own and customize my own environment.

]]>2013-10-17T08:00:00-07:00http://jimkubicek.com/blog/2013/10/17/staad-backpackJust a few weeks ago Waterfield Designs released their first pack, the Staad Backback. Strangely enough, every review I’ve seen is just a regurgitation of the press release and the product page, so I thought I’d give a little write-up after actually handling the pack.

First, my current backpack is the Tom Bihn Smart Alec. This is the best backpack I have ever owned. It’s comfortable, it’s durable, it’s sufficiently waterproof to ride my bike to work in a downpour. It has the most usable pocket system I’ve ever seen in a backpack. It’s also a bit big for what I need day-to-day, so I’ve been casually browsing around for a something smaller to get me back and forth to work.

After seeing my at the Staad, I decided to go with the waxed canvas, chocolate leather slim version of the bag. I went back and forth on the sizing, but I currently have a 13” laptop and a bag big enough to haul groceries in, so if I’m going to buy a new bag I might as well go with the smallest bag that’s useful.

First Impressions

As I write this, I have just recived the pack, so I don’t have any real usage notes to report. Here are my first impressions; things that I was wondering about, I’ve seen people ask about or details that surprise me.

The buckle is not vintage. Every review I’ve read mentions the “vintage” buckle. I think what they mean is it is a “vintage style” buckle. The buckle itself is brand-new and plastic. That being said, it’s an interesting buckle. If you watch Gary’s video notice how smoothly he opens the flap. It really is that smooth. The video glosses over the closing action a bit and makes it hard to see the exact mechanism for closing the bag. When you want to close the bag, you push the main tab down, then manipulate the small plastic bit through the slot. On a brand new Staad this is easy, as the stiffness of the webbing and the leather tab keeps everything in place and ready to close. I’m interested to see how this changes as the bag ages and everything breaks in.

Here are some animations illustrating the opening and closing action:

This clasp is fun to operate. It is one of the most satisfying closures I’ve used, rivaling the feeling you get when you rip open the fly on old broken-in button fly jeans.

The outside pockets are small, best suited to thin objects. I’ve got medium sized hands, the pockets are almost the exact size of my hands. Too small for a Moleskine, just right for Field Notes. You aren’t going be fitting a water bottle in here. These pockets are best suited for small items, earbuds, wallets, notebooks, gum, etc. Because of the stiffness of the waxed canvas, the pockets don’t stretch or deform, so you aren’t going to be able to cram a lot of stuff in there even if you wanted to.

I didn’t notice this in any images or descriptions, but the laptop and iPad pockets have a very nice fleece lining. The iPod pocket is thin, just big enough for a bare iPad (I couldn’t put my iPad mini + cover in the pocket without the cover sliding off).

I had two bottles of wine in the house. Both fit into the main compartment easily and I think I could have fit a third in there. This assumes that none of the other pockets have anything bulky in them. The pocket tapers towards the top, so putting the wine in requires unzipping the zipper. Once zipped it is fairly secure and the wine doesn’t fall out even when the bag is inverted. There’s no way you could fit a six-pack without taking the bottles out of the carrier.

The main compartment won’t fit anything much bigger than a long-sleeved t-shirt. Pack light.

Laptop sleeve ends about 2 inches above the bottom of the bag. You’d have to set the bag down very hard to have the laptop bump.

The interior pockets close with Velcro, but it’s a nice Velcro. The loop part is tight, the hook part is not rough or scratchy; it’s almost smooth. The pockets are not deep. A Field Notes notebook sticks up enough that the velcro closure cannot close.

This is probably obvious to everyone considering this bag, but it’s worth being explicit: this bag is going to get a worn look very quickly. The leather flap already has scratches on it from me opening and closing the clasp. The waxed canvas has some scuffs. Anyone considering buying this bag probably desires the broken-in look, but if you like your gear to keep looking pristine, this is likely not the bag for you.

]]>2013-08-08T09:40:00-07:00http://jimkubicek.com/blog/2013/08/08/amend-files-to-previous-commitI run into this frequently when doing big a big refactor. I’m carefully committing my changes in nice bisectable units, but then Woah! there’s a change that should be included in a previous commit. Here’s how you fix this up in Git.

Disclaimer: We are modifying Git history. Do not do this if you have already pushed these changes.

The first command commits your changes, but modifies the commit message to be the same as 8681487 with “fixup!” appended in front. Running rebase in interactive mode with “autosquash” turned on will move our previous commit right after the commit we’d like to modify and update that commit with our new changes.

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.

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.

2013-04-22 10:59:38.194 Sing![14105:2203] Loggin'
PID^^^^^

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!

]]>2013-01-27T13:57:00-08:00http://jimkubicek.com/blog/2013/01/27/list-rake-tasks-by-defaultI add this to all my Rakefiles.

123

task:defaultdosystem"rake --tasks"end

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.

]]>2013-01-26T23:53:00-08:00http://jimkubicek.com/blog/2013/01/26/unit-testing-parse-cloud-codeLike 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.

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:

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.

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.

]]>2013-01-17T07:51:00-08:00http://jimkubicek.com/blog/2013/01/17/spacing-warning-jslintI’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.

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.

]]>2012-10-16T23:36:00-07:00http://jimkubicek.com/blog/2012/10/16/testing-iskindofclassI’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:

]]>2012-10-11T16:00:00-07:00http://jimkubicek.com/blog/2012/10/11/using-uiviewSometimes 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.

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:

TL;DR

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.

]]>2012-10-02T08:18:00-07:00http://jimkubicek.com/blog/2012/10/02/sensationalistThis 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.

]]>2012-09-20T20:56:00-07:00http://jimkubicek.com/blog/2012/09/20/sort-methods-with-automatorBig 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:

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.

]]>2012-09-06T22:22:00-07:00http://jimkubicek.com/blog/2012/09/06/warningsA 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.
]]>2012-08-28T15:24:00-07:00http://jimkubicek.com/blog/2012/08/28/adium-and-imessageI 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!

(master)> git push
...
To git@github.com:jkubicek/my_proj.git
21b430d..dd378ca master -> master
! [rejected] release -> release (non-fast-forward)
error: failed to push some refs to 'git@github.com:jkubicek/my_proj.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart. If you did not intend to push that branch, you may want to
hint: specify branches to push or set the 'push.default' configuration
hint: variable to 'current' or 'upstream' to push only the current branch.

I can only blame this on my utter laziness, because the answer is right in the error text. Run the following command to configure git push to only push your current branch.

git config --global push.default current

I should have done this months ago.

]]>2012-08-09T11:11:00-07:00http://jimkubicek.com/blog/2012/08/09/dont-lazy-load-your-viewsI seem to run accross a lot of developers lazily loading their properties. As an example:

At least in iOS developement, I suspect this is caused by Apple’s sample code, particularly Apple’s default setup for Core Data projects. There are some valid reasons why you’d want to lazily load a resources, but there’s lots of great reasons why you shouldn’t. Here’s a few:

Property calls should not have side effects

There are lots of exceptions for setters (like updating the UI after setting a property), but there are very few exceptions for getters. You shouldn’t need to worry about your object changing state when you access a property.

Lazy loading is confusing

self.myTextLabel = nil;
if (self.myTextLabel) {
NSLog(@"What the shit? How did I get here?");
}

Now your label will have different text depending on whether you set myTitle before or after you access myTextLabel.

Lazy loading leads weird code

Like this:

if(self.myTextLabel) // just need to setup my text label

Initialization, layout, UI updates should be localized

You should be performing all initialization in the init method, UI updates in an update UI method and layout in layoutSubviews. Not only does this make debugging far easier (having layout issues? I feel bad for you, son. I’ve got 99 problems, but performing view layout anywhere other than layoutSubviews isn’t one.), but it ensures that your view is always in a consistent state. Big Nerd Ranch has a great writeup on why this is important.

Clearly there are exceptions to all these rules and situations where lazily loading your view properties is the right thing to do. But remember, always write code that emphasizes clarity first and optimize for speed or memory constraints later.

]]>2012-07-18T22:19:00-07:00http://jimkubicek.com/blog/2012/07/18/ok-for-serious-this-timeOK. This is a fresh start. I think I’ve got this blogging thing figured out for once. I’m using Octopress to create the site. I attempted to install Octopress a few months ago, but ran into a whole host issues trying to get ruby 1.9.2 to build. Luckily, Ruby 1.9.3 seems to fix all my issues, and installed smooth as silk. I never really got a chance to use Octopress 1.x, but 2.0 is going great. Here’s what I wanted in a blogging platform.

Pre-rendered HTML pages I don’t have any illusions about the amount of traffic I’ll be getting, so performance isn’t that a concern for me. I do want to avoid the “black box” of PHP and MySQL that I’d been used to with Wordpress. The chances of me learning every little detail of the blogging platform are slim, but if I do decide to dive in, I want it to be as easy and as frictionless as possible. Octopress is just a bunch of scripts. Nothing sneaky there!

Easy to modify A little bit of HTML, a bit of javascript, maybe a little ruby. Writing themes and modifying the behavior of the site is something well within my reach.

Run the site locally Right out of the box, Octopress makes it easy to get a full version of your site served locally. Try that, Wordpress!

Text only input I want to be able to write a blog post from anywhere on any device. Having plain text input ensures that I’ll have no excuses if I want to get something written. Plus, if I need to search my entries or make bulk changes, I’ve got my command line tools right here. Oh, and shit, I can also sit in coffee shops running full-screen Vim (green text on black background) to look like an über-hacker.

Good code formatting I’d like to make this a mostly develpment blog. Good code formatting is important. Easy code formatting is just as important.

Most importantly, I’ve got a pretty sizeable chunck of writing saved up and ready to deploy. I’m hoping I can just throw these files in my favorite text editor and hit “publish”. I’m sure a few will get thrown out in the editing process, but I’m hoping that I use those first few posts to build up some intertia.