I’m not even home from the more than excellent NSConference in Leicester, but had to hack on something super awesome that Evan Doll of Flipboard presented earlier today. They added keyboard support to UIAlertView and UIActionSheet (amongst other things) - simply to make debugging in the Simulator faster by accepting ESC and Enter keys - something that Apple should have done anyway. There’s not much value in shipping this in release builds except better support for bluetooth keyboards. And since this hack uses private API AND accesses a struct whose memory layout could change, I don’t recommend shipping it. If you do, make sure that you white-list iOS versions and block this method by default on unknown future versions of iOS. I’m using it in PSPDFKit only when compiled in DEBUG mode for the Simulator.
#define GSEVENT_TYPE 2#define GSEVENT_FLAGS 12#define GSEVENTKEY_KEYCODE 15#define GSEVENT_TYPE_KEYUP 10// http://nacho4d-nacho4d.blogspot.co.uk/2012/01/catching-keyboard-events-in-ios.html__attribute__((constructor))staticvoidPSPDFKitAddKeyboardSupportForUIAlertView(void){@autoreleasepool{// Hook into sendEvent: to get keyboard events.SELsendEventSEL=NSSelectorFromString(@"pspdf_sendEvent:");IMPsendEventIMP=imp_implementationWithBlock(^(id_self,UIEvent*event){objc_msgSend(_self,sendEventSEL,event);// call original implementation.SELgsEventSEL=NSSelectorFromString([NSStringstringWithFormat:@"%@%@Event",@"_",@"gs"]);if([eventrespondsToSelector:gsEventSEL]){// Key events come in form of UIInternalEvents.// They contain a GSEvent object which contains a GSEventRecord among other things.int*eventMem=(int*)[eventperformSelector:gsEventSEL];if(eventMem){if(eventMem[GSEVENT_TYPE]==GSEVENT_TYPE_KEYUP){UniChar*keycode=(UniChar*)&(eventMem[GSEVENTKEY_KEYCODE]);inteventFlags=eventMem[GSEVENT_FLAGS];//NSLog(@"Pressed %d", *keycode);[[NSNotificationCenterdefaultCenter]postNotificationName:@"PSPDFKeyboardEventNotification"object:niluserInfo:@{@"keycode":@(*keycode),@"eventFlags":@(eventFlags)}];}}}});PSPDFReplaceMethod(UIApplication.class,@selector(sendEvent:),sendEventSEL,sendEventIMP);// Add keyboard handler for UIAlertView.SELdidMoveToWindowSEL=NSSelectorFromString(@"pspdf_didMoveToWindow");IMPdidMoveToWindowIMP=imp_implementationWithBlock(^(UIAlertView*_self,UIEvent*event){objc_msgSend(_self,didMoveToWindowSEL,event);// call original implementation.staticcharkPSPDFKeyboardEventToken;if(_self.window){idobserverToken=[[NSNotificationCenterdefaultCenter]addObserverForName:@"PSPDFKeyboardEventNotification"object:nilqueue:nilusingBlock:^(NSNotification*notification){NSUIntegerkeyCode=[notification.userInfo[@"keycode"]integerValue];if(keyCode==41)/* ESC */{[_selfdismissWithClickedButtonIndex:_self.cancelButtonIndexanimated:YES];}elseif(keyCode==40)/* ENTER */{[_selfdismissWithClickedButtonIndex:_self.numberOfButtons-1animated:YES];}}];objc_setAssociatedObject(_self,&kPSPDFKeyboardEventToken,observerToken,OBJC_ASSOCIATION_RETAIN_NONATOMIC);}else{idobserverToken=objc_getAssociatedObject(_self,&kPSPDFKeyboardEventToken);if(observerToken)[[NSNotificationCenterdefaultCenter]removeObserver:observerToken];}});PSPDFReplaceMethod(UIAlertView.class,@selector(didMoveToWindow),didMoveToWindowSEL,didMoveToWindowIMP);}}
You also need some swizzling helpers, here’s what I use:
1234567891011121314151617
// http://www.mikeash.com/pyblog/friday-qa-2010-01-29-method-replacement-for-fun-and-profit.htmlstaticvoidPSPDFSwizzleMethod(Classc,SELorig,SELnew){MethodorigMethod=class_getInstanceMethod(c,orig);MethodnewMethod=class_getInstanceMethod(c,new);if(class_addMethod(c,orig,method_getImplementation(newMethod),method_getTypeEncoding(newMethod))){class_replaceMethod(c,new,method_getImplementation(origMethod),method_getTypeEncoding(origMethod));}else{method_exchangeImplementations(origMethod,newMethod);}}voidPSPDFReplaceMethod(Classc,SELorig,SELnewSel,IMPimpl){Methodmethod=class_getInstanceMethod(c,orig);if(!class_addMethod(c,newSel,impl,method_getTypeEncoding(method))){PSPDFLogError(@"Failed to add method: %@ on %@",NSStringFromSelector(newSel),c);}elsePSPDFSwizzleMethod(c,orig,newSel);}
There seems to be quite someconfusion around the net when it comes to the best way to center a view within an UIScrollView.
And it’s actually not that easy to get right. In PSPDFKit v1 I used the Apple recommended way (see their Photo example) of subclassing layoutSubviews. This was “good enough” until I added smart zoom in version 2 of my PDF framework. (That is, text block are detected and zoomed onto with a double tap, just like you’re used to in Mobile Safari). I noticed that the zoomToRect method did not work properly, the final rect was offset - and it was quite obvious why, since the layoutSubview-method moved around the frame of the view that was zoomed on. And don’t try to compensate this moving - it seems quite impossible to get right.
The next generation (PSPDFKit 2.2 and upwards) used override setContentOffset: to always center the content. This works, but has the drawback that you can’t pan the view around when you’re zooming out more - it’s always fixed centered. This solution also has a very nasty hidden bug where the UIScrollView can be “locked up” and don’t accept any touches anymore until you perform a pinch in/out. I’ve had an Apple DTS against this and even they only came up with useless workarounds. (like not using gesture recognizers… right.) It’s hard to reproduce this bug here without open sourcing half of my framework, so please just trust me on that one.
I’ve asked around on Twitter (thanks, everyone!) and most recommendations were about overriding layoutSubviews. Some suggested stuffing the view into another view and doing the centering manually (which I tried) but this has the drawback that you can scroll into the empty space when zoomed in (or you adapt the view and get the same problem as you had in layoutSubviews).
The solution that works by far best is by setting contentInset. It allows to pan around the view when zoomed out and doesn’t expose the “lock” bug that overriding setContentOffset: had. It also works fine with using zoomToRect. There are a few gotchas when using edgeInsets as well - for example I have a mechanism that preserves the current view state (page, zoom, contentOffset) and restores that later on. If you set contentOffset to 0,0 this will un-center your image (in contrast to method 1 and 2). But you can trigger re-centering with following trick:
123
// Trigger a new centering (center will change the content offset)scrollView.contentInset=UIEdgeInsetsZero;[scrollViewensureContentIsCentered];
I’ve made a small GitHub project that shows off all three centering techniques and zooms to a small rect on double tap (to show off the zoomToRect problem). Hopefully this helps someone save a few hours!
UIAppearance hardly is a new technologly since it was first introduced at WWDC 2011, but it still doesn’t have the adoption it deserves (guilty as charged here as well). Since now most apps are IOS5 only, there’s no excuse anymore to not adopt it. Also chances are quite high that at least some properies of your classes already support UIAppearance implicitely - since the preprocessor macro to ‘enable’ UIAppearance is actually defined to be empty:
#define UI_APPEARANCE_SELECTOR
In the simplest case, add UI_APPEARANCE_SELECTOR to your properties to inform others that this property can be set via an UIAppearance proxy. There are however some gotchas that are not clearly mentioned in the documentation, and it’s always interesting how something like this works behind the scenes. (This is not a tutorial - go ahead and read Apple’s documentation on UIAppearance if you’ve never used it before)
From looking at the debugger, UIAppearance is quite smart and only applies properties before the view is added to a window.
UIAppearance mostly is for UIView subclasses, with some exceptions like UIBarItem (and UIBarButtonItem) who internally handle their respecive view. For those classes Apple implemented a custom apperance proxy (_UIBarItemAppearance).
Let’s start with a simple example, converting this class (taken from my iOS PDF SDK) to work with UIAppearance:
12345678910111213141516171819202122
/// Simple rounded label.@interfacePSPDFRoundedLabel : UILabel/// Corner radius. Defaults to 10.@property(nonatomic,assign)CGFloatcornerRadius;/// Label background. Defaults to [UIColor colorWithWhite:0.f alpha:0.6f]@property(nonatomic,strong)UIColor*rectColor;@end@implementationPSPDFRoundedLabel-(id)initWithFrame:(CGRect)frame{if(self=[superinitWithFrame:frame]){self.rectColor=[UIColorcolorWithWhite:0.falpha:0.6f];self.cornerRadius=10.f;}returnself;}-(void)setBackgroundColor:(UIColor*)color{[supersetBackgroundColor:[UIColorclearColor]];self.rectColor=color;}// drawRect is trivial@end
Simply adding UI_APPEARANCE_SELECTOR will not work here. One gotcha is that UIAppearance swizzles all setters that have a default apperance, and tracks when they get changed - so that UIAppearance doesn’t override your customizations. This is a problem here, since we use setters in the initializer, and for UIAppearance it now looks as we already customized the class ourselves.
Lesson: Only use direct ivar access in the initializer for properties that comply to UI_APPEARANCE_SELECTOR.
123456789101112131415161718192021222324252627
/// Simple rounded label.@interfacePSPDFRoundedLabel : UILabel/// Corner radius. Defaults to 10.@property(nonatomic,assign)CGFloatcornerRadiusUI_APPEARANCE_SELECTOR;/// Label background. Defaults to [UIColor colorWithWhite:0.f alpha:0.6f]@property(nonatomic,strong)UIColor*rectColorUI_APPEARANCE_SELECTOR;@end@implementationPSPDFRoundedLabel{BOOL_isInitializing;}-(id)initWithFrame:(CGRect)frame{_isInitializing=YES;if(self=[superinitWithFrame:frame]){_rectColor=[UIColorcolorWithWhite:0.falpha:0.6f];_cornerRadius=10.f;}_isInitializing=NO;returnself;}-(void)setBackgroundColor:(UIColor*)color{[supersetBackgroundColor:[UIColorclearColor]];// Check needed for UIAppearance to work (since UILabel uses setters in init)if(!_isInitializing)self.rectColor=color;}// drawRect is trivial@end
This class now fully works with UIAppearance. Notice that we had to do some ugly state checking (_isInitializing), because UILabel internally calls self.backgroundColor = [UIColor whiteColor] in the init, which then calls the setRectColor, which would already could as “changed” for UIAppearance. Notice the TaggingApperanceGeneralSetterIMP that Apple uses to track any change to the setter:
I’m using following code to test the customizations:
We can also use the runtime to query at any point what apperance settings there are for any given class. This is only meant to be used within the debugger, since it uses private API to query _UIAppearance.
That’s it, the class is fully compatible with UIAppearance. When using this inside a framework, you should write custom UIAppearance rules instead of manually setting the property, to allow to override those rules from the outside (remember, manually setting a property will disable it for apperance usage). +load is a good time for that. There are some more gotchas on UIAppearance like BOOL not being supported (use NSInteger instead), and some honorable exceptions that do support apperance selectors, like DACircularProgress.
While developing a new version of PSPDFKit, I started using UIMenuController more and more. The first thing you’ll notice is that it’s different from your typical target/action pattern: the target is missing.
This is partly actually pretty genius. iOS checks if the @selector can be invoked calling canPerformAction:withSender: which is part of UIResponder. If the object returns NO, the system walks up the UIResponder chain until it finds an object that returns YES or nextResponder returns nil.
A typical resonder chain looks like this: UIView -> UIViewController -> UINavigationController -> UIApplication -> AppDelegate.
Now this is great in theory, if you implement e.g. copy: on your viewController, the firstResponder can be any subview and it still works. In practice however I found this more limitating and annoying. And I’m not the only one.
Especially if your menus get more complex, your code is littered with selectors. So let’s write a block-based subclass. Enter PSMenuItem.
123
PSMenuItem*actionItem=[[PSMenuItemalloc]initWithTitle:@"Action 1"block:^{NSLog(@"Hello, from a block!");}];
My naive approach was to just use one common selector internally and execute the block that is saved in the PSMenuItem subclass. The only problem: (id)sender of the action gets called with the UIMenuController. This is wrong on so many levels, especially since UIMenuController is a singleton anyway. There’s no easy way to know what UIMenuItem has been pressed.
But since I already was committed in writing the subclass, that couldn’t stop me. We just create a unique selector for each UIMenuItem, and catch execution at a lower level.
Enter Cocoa’s Message Forwarding
If the runtime can’t find a selector on the current class, message forwarding is started. (That’s the tech that allows classes like NSUndoManager or NSProxy.)
Lazy method resolution:resolveInstanceMethod: is called. If this returns YES, message sending is restarted as the systme assumes that the method has been added at runtime. We could theoretically use this and add a method that calls the block at runtime. But this would pollute the object with many new methods - not what we want.
Fast forwarding path:-(id)forwardingTargetForSelector:(SEL)sel has been added in Leopard as a faster approach to the NSInvocation-based message forwarding. We could use this to react to our custom selector, but we would have to return an object that implements our selector (or does not throw an exception with undefined methods.) Possible candidate, but there’s something better.
Normal forwarding path: This is the “classic” message forwarding that exists since the old days. Here actually two methods are called. methodSignatureForSelector:, followed by forwardInvocation:. (The method signature is needed to build the NSInvocation). PSMenuItem hooks into both of those methods. But let’s go step by step through PSMenuItem’s + (void)installMenuHandlerForObject:(id)object
12345
+(void)installMenuHandlerForObject:(id)object{@autoreleasepool{@synchronized(self){// object can be both a class or an instance of a class.ClassobjectClass=class_isMetaClass(object_getClass(object))?object:[objectclass];
Note the @synchronized, swizzling is not thread save. Also we add an @autoreleasepool here, as this could be executed from +load or +initialize; at a very early time where’s no default NSAutoreleasePool in place yet.
class_isMetaClass checks if object_getClass returns a class or a meta-class. This is needed because object can both be a instance of a class or a class object itself, and you can’t just invoke a isKindOfClass on a Class object. If you’re wondering what a meta-class is; it’s basically a class that defines methods available on the class. CocoaWithLove has a great article on that.
123456789101112
// check if menu handler has been already installed.SELcanPerformActionSEL=NSSelectorFromString(@"pspdf_canPerformAction:withSender:");if(!class_getInstanceMethod(objectClass,canPerformActionSEL)){// add canBecomeFirstResponder if it is not returning YES. (or if we don't know)if(object==objectClass||![objectcanBecomeFirstResponder]){SELcanBecomeFRSEL=NSSelectorFromString(@"pspdf_canBecomeFirstResponder");IMPcanBecomeFRIMP=imp_implementationWithBlock(PSPDFBlockImplCast(^(id_self){returnYES;}));PSPDFReplaceMethod(objectClass,@selector(canBecomeFirstResponder),canBecomeFRSEL,canBecomeFRIMP);}
Here we test if the class has already been swizzled by us with using class_getInstanceMethod. Again, because object might be a Class already, we can’t just use respondsToSelector:. Next, we test if we should add a handler to canBecomeFirstResponder. This is needed to make the UIMenuController display in the first place.
Note the imp_implementationWithBlock. This is a new method in iOS4.3 upwards, but has just a much nicer syntax and is more compact than classic C functions. There’s another small annoyance, PSPDFBlockImplCast. The syntax of imp_implementationWithBlock was slightly changed in yet to be released versions of Xcode, older versions still need the (__bridge void *) cast, newer versions will complain and only work without.
PSPDFReplaceMethod is a helper that first adds the new method via our pspdf_ selector name, then swizzles the original implementation with our custom implementation.
123456
// swizzle canPerformAction:withSender: for our custom selectors.// Queried before the UIMenuController is shown.IMPcanPerformActionIMP=imp_implementationWithBlock(PSPDFBlockImplCast(^(id_self,SELaction,idsender){returnPSIsMenuItemSelector(action)?YES:((BOOL(*)(id,SEL,SEL,id))objc_msgSend)(_self,canPerformActionSEL,action,sender);}));PSPDFReplaceMethod(objectClass,@selector(canPerformAction:withSender:),canPerformActionSEL,canPerformActionIMP);
Next up, we swizzle canPerformAction:withSender:. This is called before the UIMenuController is displayed. If we detect our custom selector (PSIsMenuItemSelector), we return YES, else we call the original implementation. Note the tricky casting on objc_msgSend. (We could also build a NSInvocation, but that would be much slower and needs much more code).
PSIsMenuItemSelector is just a shorthand for return [NSStringFromSelector(selector) hasPrefix:kMenuItemTrailer];
Finally we arrive at the method that’s called during message forwarding, when the user selects a UIMenuItem. We again check for the selector and return a faked NSMethodSignature. If we wouldn’t return a signature here, we’d get a selector not implemented exception. "v@:@" is the selector encoding for -(void)action:(id)sender. v is the return type (void), the first @ is self, the : is the selector (_cmd), the @ finally is id sender. You can learn more on Apple Developer about objc type encodings.
123456789101112131415161718
// swizzle forwardInvocation:SELforwardInvocationSEL=NSSelectorFromString(@"pspdf_forwardInvocation:");IMPforwardInvocationIMP=imp_implementationWithBlock(PSPDFBlockImplCast(^(id_self,NSInvocation*invocation){if(PSIsMenuItemSelector([invocationselector])){for(PSMenuItem*menuItemin[UIMenuControllersharedMenuController].menuItems){if([menuItemisKindOfClass:[PSMenuItemclass]]&&sel_isEqual([invocationselector],menuItem.customSelector)){[menuItemperformBlock];break;// find corresponding MenuItem and forward}}}else{objc_msgSend(_self,forwardInvocationSEL,invocation);}}));PSPDFReplaceMethod(objectClass,@selector(forwardInvocation:),forwardInvocationSEL,forwardInvocationIMP);}}}}
Finally, the last piece. After methodSignatureForSelector returned a valid NSMethodSignature, the system builds a NSInvocation object that we can handle (or not). Here we load the selector, loop through all menuItems in the UIMenuController and finally call the block on the PSMenuItem, if found. Note that we could also extract UIMenuController from the NSInviation itself, but since it’s a singleton, there’s no need for that.
One, simple piece remains. We build up the custom selector in our initWithTitle:block:
123456
// Create a unique, still debuggable selector unique per PSMenuItem.NSString*strippedTitle=[[[titlecomponentsSeparatedByCharactersInSet:[[NSCharacterSetletterCharacterSet]invertedSet]]componentsJoinedByString:@""]lowercaseString];CFUUIDRefuuid=CFUUIDCreate(kCFAllocatorDefault);NSString*uuidString=CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault,uuid));CFRelease(uuid);SELcustomSelector=NSSelectorFromString([NSStringstringWithFormat:@"%@_%@_%@:",kMenuItemTrailer,strippedTitle,uuidString]);
I’ve used a UUID to even allow menu items with the same title, they else would generate the same selector and would potentially call the wrong block.
Now that Xcode 4.4 finally has reached Golden Master and you can submit apps, here’s a trick to use subscriptingright now. Yes, Apple will introduce this feature in a future version of OS X and iOS, but why wait? Here’s the snippet from PSPDFKit, my iOS PDF framework to make it work:
It’s a bit crude, and Xcode won’t show any warnings if you’re doing subscripting on any object now, but you know what you’re doing, right? Furthermore this is only temporary, to make it compile with Xcode 4.4. In Xcode 4.5, this snippet won’t do anything and isn’t needed anymore, since the new SDK already has those methods defined on the classes you care about. Just make sure this is in your global header file. (e.g. precompiled headers)
Note that unlike literals, who are really just syntactical sugar and already work great in Xcode 4.4+ (LLVM 4.0+), subscripting actually calls into new methods. So how does this “magically defining headers” actually work?
The subscripting compatibility shim is actually part of ARCLite. The ARCLiteload function takes care of dynamically adding the four subscript methods with class_addMethod. The implementations of these methods simply call the equivalent non-subscript methods.
If you, for any reason, are not on ARC yet, you really want to force the compiler to link with libarclite using the -fobjc-arc linker flag. This works all the way back to iOS 4.3.
Also check out the new Xcode Refactoring Assistant to convert your codebase to Modern Objective-C. It’s awesome.
While working on PSPDFKit, I more and more embrace viewController containment to better distribute responsibilities between different view controllers.
One thing that always annoyed me about that is that po [[UIWindow keyWindow] recursiveDescription] is less and less useful if you just see a big bunch of UIView’s.
I asked some engineers at WWDC if there’s something like recursiveDescription, just for UIViewControllers, but they didn’t had a answer on that, so I finally wrote my own.
Regular output of po [[UIWindow keyWindow] recursiveDescription]
Pimped output:
The solution is surprisingly simple. Add the following code somewhere to your project and you’re done.
As a bonus, this also lists attached childViewControllers if you run iOS5 or above, and it will show you if a childViewController has a greater frame than it’s parentViewController (this is usually a easy to miss bug).
Note the usage of __attribute__((constructor)), this will call the method at a very early stage on app loading. (thus we need an explicit @autorelease pool).
Works with or without ARC, iOS 4.3 and above. (imp_implementationWithBlock requires iOS 4.3, unless you want to perform some dark magic.)
For those if you that are curious, I use a private API call (_viewDelegate), but that’s obfuscated (it would pass a AppStore review) and you really only should compile that function in DEBUG mode anyway.
While writing AFDownloadRequestOperation, a new subclass for AFNetworking I discovered that the behavior of NSURLCache changed between iOS 4.x and iOS 5.x.
As of iOS5, NSURLCache automatically saves responses to disk. I haven’t found anything the release notes that confirms the change, but I tried it both with iOS 4.3/5.0/5.1 on the simulator and the device, and with every 5.x version a disk cache file is created and populated. This is great, as many developers probably aren’t aware of this and the system just does the right thing - and it’s fast.
If the Cache-Control headers indicate that this request can be cached, iOS automatically saves it to a local sqlite cache file in AppDirectory/Caches/(bundleid)/Cache.db. E.g. public, max-age=31536000 marks that the request cache will be valid for a year, as max-age is listed in seconds.
The sqlite scheme for the cache looks identical with the one used in OS X:
So, why should you care? Well, the Cache.db caches any file that has a correct Cache-Control header set. Thus, if you download a pdf document, it might end up in your disk cache as well, taking up twice the memory.
The default NSURLCache will be used, with a disk limit of 20MB. You can easily test this with gdb/lldb:
1
p (int)[[NSURLCache sharedURLCache] diskCapacity]
The memoryCapacity defaults to 40MB, although the cache will clear itself in low memory situations.
With creating NSURLRequest using requestWithURL:cachePolicy:timeoutInterval:, you can define the cachePolicy, but this only allows you to choose how if and how the cache will be read.
Available options are: only use the cache value (NSURLRequestReturnCacheDataDontLoad), try the cache and load if different (NSURLRequestReturnCacheDataElseLoad) or ignore cache entirely (NSURLRequestReloadIgnoringLocalCacheData).
The default option, if not set explicitly, is NSURLRequestUseProtocolCachePolicy, which most of the time is equivalent to NSURLRequestReturnCacheDataElseLoad, thus uses the cache if the object hasn’t changed. There are a few other options in the enum, but those are unimplemented.
Note: There doesn’t seem a way to force caching of certain requests, connection:willCacheResponse: is only called if the response contains a Cache-Control header, according to Apple’s documentation:
The delegate receives connection:willCacheResponse: messages only for protocols that support caching.
If you’re not yet using AFNetworking, you really should. It’s a big step forward compared to classical NSURLConnection handling, even if Apple recently added a few new fancy shorthands in iOS5. In AFNetworking, your network operations are indeed subclasses of NSOperation, which allows a much better control what’s currently running, and AFHTTPClient is the perfect base class to implement any API.
A few days ago I booked my flight back to Austria. Starting with April 13, I’m a full-time indie again.
You gonna say, what! You’re leaving the Bay Area? This is sad! But I’m very excited about it.
I’m in a better situation than ever. I finally figured out what I wanna do with my life. I’m no longer enviously looking at other places. I learned what’s really important. And that you can’t just replace life-long friends.
Don’t get me wrong. I’m gonna miss San Francisco. Really. Such a great city. Such an awesome spirit; unlike any other city I’ve ever been to. And heck, half of my Twitter followers are here, so super-nice to finally meet up with you guys!
So why leave at all? Well, it just didn’t work out. I’m full of ideas and really, really wanna work on my own stuff.
Back when I got my job offer at a WWDC party in 2011, I was in a whole different position, worked. as. a. freelancer. for some nice companies, but wanted a change. So the prospect of living in San Francisco, being part of the startup culture, working together on something great, was very, very appealing. (damn you, Hacker News!)
So, I accepted the offer and waited for my visa. Waited, and waited. I stopped doing freelance work because initially we thought it’d all be done in a month. Ha, how wrong we were. In the end it took more than 6 month! I even finished my bachelors degree during that time.
Not only that. Suddenly my mind was free from all the freelance work (and the feeling of guilt when I didn’t work on them). Naturally, I filled that space up with other. projects. And, partly inspired by some friends, I wanted to try the paid component business. So this happened. In the end, while waiting for my visa, I’ve created a viable business that’s now making more money than my full-time job possibly ever could.
All gears where set for SF, so I took the gig, it was all about the experience now. I really believed I could do this. But then, managing a 40h+ job with basically another full-time job on the side is nearly impossible, and after killing myself for a while, I finally had to choose which is more fun. Well, let’s say it wasn’t a hard decision. (To be correct, it was very hard. I hate letting people down, and of course while they’re a business, I also respected them, and had a hard time to disappoint their high expectations they had in me.)
This all sounds so simple and logical now, but I really jumped into the whole business and landed on my feet. Support requests and ideas are exploding, and as revenue goes up, so does the amount of time to care about my product. Also, I was really looking forward to work wit some well-respected people in the iOS scene, only to find out that they had already left the company before I came here.
Lastly, NSConference gave me the final kick. Such an amazingly great amount of inspiring people that genuinely love what they do - you can’t just go back to your 11-7 job after experiencing that. Also, meeting customers that use your product and really love it is the sweetest thing ever.
I have no regrets on trying it, and I’m very thankful for the opportunity they’ve given me - in fact it’s one of the best things ever happened to me! It gave me the guts to go full-indie, without even thinking about it. It helped me to figure out what I really wanna do with my life.
So, what’s next? Well, I’ve big plans with making PSPDFKit even better… and then there’s this other app idea, that’s crossing my mind way too often. I’m building this for myself, because I really, really want it. And every time I did that, it turned out to be a great success. If you wanna hear more about it, you should follow me on Twitter.
And about San Francisco, I’ll probably be back pretty soon ;)
You’re using KVO, right? So you most likely already have written code like this:
Carefully encapsulating your calls within a willChangeValueForKey/didChangeValueForKey call to “enable” KVO.
Well, turns out, you just did shit work. There’s no reason to do the will/did dance, as long as you are using a setter method to change the ivar. It doesn’t need to be backed by an ivar or declared as a property. KVO was written long before there was anything like @property in Objective-C.
In fact, I am now writing iOS apps for about 4 years and didn’t know this. A lot. of. open. source. code. also gets this wrong. Apple has some good KVO documentation, where they explain the concept of Automatic Change Notifications.
Sometimes you also might wanna optimize how often you’re sending KVO notifications with overriding automaticallyNotifiesObserversForKey: to disable automatic change notifications for certain properties.
In this example, there might be expensive KVO observations when the image changes, so we wanna make damn sure that KVO is only fired if the image actually is a different one to the already set image:
If you currently have such obsolete calls, they’re not doing any harm. Incrementally called willChangeValueForKey doesn’t emit more notifications. Still, time to delete some code!
Update: Don’t forget that there are more ways that’ll save you manual calls to will/did, like using the little known addition keyPathsForValuesAffecting(PropertyName), which uses some runtime magic to make KVO smarter. Here’s a real-life example how I used that on AFNetworking, so people can register a KVO notification on “isNetworkActivityIndicatorVisible” and it’ll get sent every time activityCount is changed. (You’ll also see that I do some atomic updating that requires manual KVO.)
I’ve rebooted my blog. Will add random bits about iOS development and some personal thoughts, especially since some of my friends complained that apparently I tweet too much (cough Amy cough :)
And they’re right. I love twitter, but sometimes you just need more than 140 characters.
The old content has been moved into limbo. Most of it would have needed some update to be valid again, so you’re not missing a lot. So if you’re coming from Google and miss a particular thing, hit me up on Twitter and I might dig it up for you.