Author Archive

Objective C Builder Pattern play

April 12, 2014

So I read two posts on the Builder Pattern from Java today that got linked to off of Twitter.

This by Klaas Pieter which referenced this one by Uli Kusterer.  Both good articles.

I haven’t done Java much at all for the last 10 years and so am not used to this pattern, but I thought about how I might do something similar and while I’m not sure my first thought is any better, it seems to meet the requirements and/or benefits noted by the two blog posts in question and the tweet discussion referencing them.

Instead of:

 Pizza pizza = new Pizza.Builder()
     .size(12)
     .pepperoni(true)
     .mushrooms(true)
     .build();

(from Uli’s post), or

  Image* theImage =
    (new Image.Builder)->SetWidth(100)
    ->SetHeight(80)->SetDepth(8)->Build();

(from Klaas’ post)

I tried something like:

Foo * aFoo = [Foo fooWithData: @{
     @"width" : @21, @"height" : @22 }];

Here’s one way to implement that - there are multiple, clearly
(pardon the formatting, trying to fit into our narrow blog them is annoying):

// .h file
#import <Foundation/Foundation.h>

@interface Foo : NSObject

+ (instancetype) fooWithData: (NSDictionary*) initParams;

@end

// .m file
@interface Foo ()
@property (nonatomic, assign) long width;
@property (nonatomic, assign) long height;
@property (nonatomic, assign) long depth;
@end

@implementation Foo

+ (instancetype) fooWithData: (NSDictionary*) initParams
{
  Foo *result = [[Foo alloc] init];

  // If one uses setValue:forKey: in a loop as
  // as Uli notes then we can't support integral
  // properties like ints.
  // Also doing it explicitly as below
  // means we don't have to have the same name
  // for our private internal properties as we
  // document for our public parameters because
  // we can map them here.
  // e.g.,
  //  result.imageWidth = [initParams[@"width"] longValue];

  if ( initParams[@"width"] != nil )
    result.width = [initParams[@"width"] longValue];

  if ( initParams[@"height"] != nil )
    result.height = [initParams[@"height"] longValue];

  if ( initParams[@"depth"] != nil )
    result.depth = [initParams[@"depth"] longValue];

  return result;
}

- (instancetype) init
{
  self = [super init];
  if ( self )
  {
    // init with defaults
    _width = 10;
    _height = 10;
    _depth = 1;
  }
  return self;
}

- (NSString*) description
{
  return [NSString stringWithFormat:
           @"Foo: (%p), width: %ld, height: %ld, depth: %ld",
           self, self.width, self.height, self.depth];
}
@end

// main.m
#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
  @autoreleasepool {
      // note no depth specified, taking default of 1
    Foo * aFoo =
      [Foo fooWithData: @{ @"width" : @21, @"height" : @22 }];
    NSLog(@"aFoo: %@", aFoo );
  }
}

Paste the above into CodeRunner and run it and you get:

2014-04-12 16:22:38.918 Untitled 7[71144:707]
aFoo: Foo: (0x7f8842c0af00), width: 21, height: 22, depth: 1

In the above I only typed in the class method as taking the full parameter list but normally I would have made the init method take the same parameter and do the initialization & mapping there. Something I’d likely add if I was going to actually use this, which I’m not likely to. Why not? Because to use the construct above you’d have to document the parameter keys available to use in the dictionary and what type of value each takes. This is where ObjectiveC’s named parameters comes in handy: they are self documenting.

Anyway, an interesting procrastination from what I was supposed to be doing this Saturday afternoon… :-)

I think Craig is right on track with his wearables & Apple

March 13, 2014

I think Craig Hockenberry @chockenberry is right on track with his Wearing Apple post.

I’ve been thinking and talking about a “personal secure network” among a collection of devices you are wearing or carrying for a while now and it seems like a no-brainer to me.  Seems totally silly to put all the battery, radios, antennas, storage and whatnot in a single device (google glass for example).

You need less battery in what I call the ‘motes’ if the LTE/WiFi radios and antennas are in the ‘core’ (“hub” in Craig’s post). What are ‘motes’ ? Think rings, earrings, necklace, bracelet, phone in pocket, flexible battery in belt, piezo generator in shoes, motion generator in umbrella/walking stick, bluetooth earpiece, display in glasses and/or contacts, high performance computing cube in our backpack, and sure, even a watch :)

What’s the problem with this vision? Lots really :)  Charging all these devices will be a pain.  Clearly you need something like a flat pad you set ‘motes’ on while you sleep and they charge inductively.  Better yet would be if they had small energy harvester chips with fractal antennas that harvested ambient energy (microwaves, cellular signals, AM, FM, etc) to extend their battery life.  Oh, yah, better batteries would be a big win and this may not get cool until that happens.

Want to get even more “out there?” Check this out:  Sugar-powered biobattery has 10 times the energy storage of lithium.  Pretty cool but one of the implications of this might be devices that could be powered from our body’s internal processes directly.  So to charge your devices you just eat more.  Be a boon for obesity.  Need to lose weight? Play more flappy birds!  :-P

This then lets us surgically implant devices so you don’t have to worry about forgetting it at home.  You may think I’m being silly, but the convenience will win people over.  Also, note the long-time existence and surgical implantation of pacemakers & defibrillators.  Then look at how common tattoos and body piercing are in youth today (in parts of the USA anyway).  We are not that far from this.

Ok Geek’s hungry so leaving it at this quick “jot this down” for now.

Brother® stops & refuses to print. Annoying! So I hack their TN-360 toner cartridges to get all the toner in them.

March 2, 2014

I purchased a Brother® MFC-7840w multifunction laser printer some years ago and I have to say that it’s one of the better modern printers I’ve owned.  Mac OS X software for it isn’t great (buggy), but it’s better than most of the others I’ve tried and the printer performs quite well.  I’ve been recommending them to anyone who’s asked me (and I get asked quite a bit).

After finishing the small starter toner cartridge they supply with the printer I put in my first TN-360 “High Yield” toner cartridge which claims 3500 pages under “normal use”.  I use this printer under what I’d consider normal conditions – mostly simple text documents.

Worked well but all of a sudden it just stopped printing with a message about the toner needed to be replaced.  “That’s odd,” I thought to myself.  “I’ve owned a lot of laser printers over the last 22+/- years and they’ve always started gradually printing more and more faintly when the toner was running out and I’ve never had a printer just refuse to print until I changed the toner cartridge before! Seems pretty heavy handed.  Then I calculated the number of pages it had printed (2120) and had an uncomfortable thought: “If they just stop and refuse to print and the printouts were looking just fine right up until that point, how do I know it’s really out of toner?”

I didn’t get my money’s worth and the forced toner replacement was feeling heavy handed and annoying.  So I wondered, “how do they decide to put up that alert anyway?”  Pulled the toner cartridge out and started examining it looking for electrical contacts (sensors inside?) or some other mechanism.  I found this:

IMG_3142

Note the arrow.  It’s pointing to a clear plastic “window” on the right side of the toner cartridge when you’re looking at the top from the front where the handle is.  It appeared like it might give the printer an optical view into the insides of the toner cartridge. “Ah HA!” I thought.  Small piece of Gorilla tape (sticks much better than electrical tape) later and I had this:

IMG_3140

Put it back in and time for a test…

Printer prints PERFECTLY… We are being ripped off by Brother and that really sucks.

This fixed worked for another 1001 perfect printouts and then it stopped again…

“DANG IT! The printouts were still looking *fine*!”

Take the toner out to put in the replacement and notice something on the side when you’re looking at the bottom:

IMG_3145

There’s Another Sensor Window!  (With Gorilla tape on it in this image).  Here’s a close-up:

IMG_3144

This piece of tape added and, sure enough, working FINE again… ARG FARG SNARG – BROTHER!  I want to like you but this is robbery!  AND it’s bad for the environment which makes it even more offensive.  Rarely do I want to call for a class action lawsuit, but this situation was definitely making me feel that way…

How many perfectly fine beautiful printouts did I get after blocking the second window?  I can’t tell you yet because it’s still going strong 200 sheets later.  :-/

So, if you want to get the full life out of your Brother TN-360 High Yield printer cartridge you may want to pick up a roll of Gorilla Tape and prepare to “fix” the cartridge.  Be careful to make sure the tape is stuck on there will because a loose piece of tape being drawn through your printer will probably do bad things to it (Follow these instructions at your own risk!).

Please add a comment if you try this with a different printer model and it works for that one also; likewise for other Brother toner cartridges. Thanks!

Cheers.

Note: All trademarks noted are the property of their respective trademark owners.

Simple BBEdit Text Filter that’s been useful: PrettyJSON.py

February 18, 2014

Dad’s been working with some JSON output from a web service lately and it comes back lacking line-feeds and indentation which is great for transmission but hard to read for humans.  Dad’s not a python programmer and Geek’s busy writing a Humanities 110 paper, but the simple python script PrettyJSON.py (below) seems to work if you put it into

~/Library/Application Support/BBEdit/Text Filters/

It can be used to beautify the front window in BBEdit if that contains JSON:


#!/usr/bin/env python
import fileinput
import json
if __name__ == "__main__":
  jsonStr = ''
  for a_line in fileinput.input():
    jsonStr = jsonStr + ' ' + a_line.strip()
  jsonObj = json.loads(jsonStr)
  print json.dumps(jsonObj, sort_keys=True, indent=2)

Because Bare Bones Software is so cool this works with their free Text Wrangler editor as well except you just put the files in

~/Library/Application Support/TextWrangler/Text Filters/

instead, as one would expect.

This gives you a new item in the “Text” -> “Apply Text Filter” sub-menu named whatever you named the file (PrettyJSON.py in my case).  Open a messy JSON file, select “Text” -> “Apply Text Filter” -> “PrettyJSON.py” and watch your file contents magically become beautiful! Thanks BBEdit!

Core Data – efficient fetching of portions of Entities

February 14, 2014

Quick write up of an active conversation on twitter and the results of some research.

Brent Simmons posted about something I’d started looking into today: Efficient Core Data fetching when you only need a few fields of a database Entity.  The name of setPropertiesToFetch: in NSFetchRequest looks promising however the documentation says:

This value is only used if resultType is set to NSDictionaryResultType.

Well that’s a bummer because we’d really like our nice subclass of NSManagedObject to be used by our view controller (say) or we only need to access one property of the complex object.  Here’s something odd I noticed though: the comment in the NSFetchRequest.h file (OS X 10.8 SDK & 10.9 SDK) for setPropertiesToFetch: says this:

If NSManagedObjectResultType is set, then NSExpressionDescription cannot be used, and the results are managed object faults partially pre-populated with the named properties

Well hey! That’s exactly what we want it to do for efficiency when we only need a couple of properties out of many for a given entity.

Thanks to some twitter dialog with @pgor and others, and especially a reminder from @JimRoepcke about setting -com.apple.CoreData.SQLDebug 1 to show the sql logging for Core Data when talking to an sqlite backend, I was able to verify that this does work the way we want it to, at least on OS X running under 10.8.4:

If you use code like the following:


NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @"AppEntry"];
[request setPredicate: [NSPredicate predicateWithFormat: @"app_id in %@", inAppIDs]];
[request setIncludesSubentities: NO];
[request setPropertiesToFetch: @[ @"app_id", @"fooprop"]];
// [request setIncludesPropertyValues: NO]; // you need YES, which is the default
[request setResultType: NSManagedObjectResultType];
[request setReturnsObjectsAsFaults: NO]; // maybe not needed.  It will still be a fault,
                                         // but the properties are preloaded
NSError * error = nil;
NSArray * fetchedArray = [self.managedObjectContext executeFetchRequest: request error: &error ];
if ( fetchedArray != nil )
{
  if ( [fetchedArray count] > 0 )
  {
    AppEntry * entry = [fetchedArray firstObject];
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
    NSNumber * appID = entry.app_id;
    NSLog(@" appID: %@", appID );
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
      // accessing property not in setPropertiesToFetch:
      // causes fault to fire & load whole object
    NSString * otherProperty = entry.otherProperty;
    NSLog(@" isFault? %@", entry.isFault ? @"YES" : @"NO" );
    NSLog(@"otherProperty: %@", otherProperty );
  }
  else
    NSLog(@"no resuts");
}

(code changed to mask client project details so typos are because of that)

and the output is:

// the fetch does this - only the two properties we indicated are fetched:
 CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.ZAPP_ID, t0.ZFOO FROM 
                  ZAPPENTRY t0 WHERE t0.ZAPP_ID IN (?,?,?)
 isFault? YES
 appID: 281940292
 isFault? YES
 CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZAPP_ID, t0.ZOTHERPROPERTY, 
                   t0.ZDATESTAMP, t0.ZNAME, t0.ZFOO, t0.ZTITLE FROM ZAPPENTRY t0 
                   WHERE t0.Z_PK = ?
 CoreData: annotation: sql connection fetch time: 0.0025s
 CoreData: annotation: total fetch execution time: 0.0030s for 1 rows.
 CoreData: annotation: fault fulfilled from database for : 0x100150590 ...
 isFault? NO
 otherProperty: it works!

So you can see that the main fetch request only grabbed the two properties that were in setPropertiesToFetch:. The result object is a faulted NSManagedObject (see where we checked isFault) but the property values for the properties listed in setPropertiesToFetch: are available without faulting the object and doing another database fetch. You’ll see we accessed appID to check this.

However, if you then access a property that was not in the setPropertiesToFetch: list (otherProperty in the above code) you can see that another sql call is made and the object is faulted and fully loaded.  The next check for isFault returns NO because it is no longer a fault.

So to me this indicates that setPropertiesToFetch: IS useful exactly as we’d like even when you’re not getting the NSDictionaryResultType and so is ideal for exactly the situation Brent was asking about for his timeline view.    I’ve filed a radar on the documentation error rdar://16073227 so hopefully that’ll get updated sooner than later.

Update:

I was curious if one could modify one of these limited properties without faulting the entire object and all of it’s properties (which seemed unlikely) and so I did an additional test and the answer is: nope.  Modifying a prefetched property on the object causes a fault and the whole object and all it’s properties are loaded into memory and isFault returns NO.

Update #2: 

So this technique above turns out to work and be handy when you only need to fetch an item in a one-to-many property/relation off of an object with lots of properties to avoid loading all those properties into memory.  In our sample data an AppEntry has a bunch of properties including a relation to a list of prices and we’d like the most recent price (just any price for this sample code) but we don’t need to load in the rest of the data in the App Entry entity.  Works like this:

NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName: @"AppEntry"];
[request setPredicate: [NSPredicate predicateWithFormat: @"app_id == %@", inAppID]];
[request setIncludesSubentities: NO];
[request setReturnsObjectsAsFaults: NO];
[request setPropertiesToFetch: @[ @"app_id" ]];
[request setRelationshipKeyPathsForPrefetching: @[ @"prices" ]];
NSError * error = nil;
NSArray * fetchedArray = [self.managedObjectContext executeFetchRequest: request error: &error ];
if ( fetchedArray != nil )
{
  if ( [fetchedArray count] > 0 )
  {
    AppEntry * appData = [fetchedArray firstObject];
    if ( appData != nil )
    {
      PriceEntry * price = [appData.prices anyObject];
      NSLog(@"a price is: %@", price.price );
    }
  }
}

and the logging looks like this:

CoreData: sql: SELECT t0.Z_ENT, t0.Z_PK, t0.ZAPP_ID FROM ZAPPENTRY t0 WHERE t0.ZAPP_ID = ?
CoreData: annotation: sql connection fetch time: 0.0005s
CoreData: sql: SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZDATESTAMP, t0.ZPRICE, t0.ZAPP_ID
   FROM ZPRICEENTRY t0 WHERE t0.ZAPP_ID IN (?) ORDER BY t0.ZAPP_ID
CoreData: annotation: sql connection fetch time: 0.0004s
CoreData: annotation: total fetch execution time: 0.0007s for 1 rows.
CoreData: annotation: Prefetching with key 'prices'. Got 1 rows.
CoreData: annotation: total fetch execution time: 0.0022s for 1 rows.
a price is: 0

So you can see that it only loads the app_id property from the AppEntry object but still you can get to the prices relation.  Unfortunately I’m not seeing a way to cascade the setPropertiesToFetch: down into the related entities and so all the fields in the PriceEntity in this example get fetched.  I’d love to find a way to do that so if you figure that out please let me know – thanks!

Update #3: 

(I know, I know! What’s with all these updates?! – I wanted to get the basics out there and then I kept thinking of other angles/aspects of this topic).

So one thing that might be helpful is to show how to use the -com.apple.CoreData.SQLDebug 1 setting to examine what Core Data is doing when you’re using it. Setting this was critical to understanding what was happening in the above research.  You want to pass this as an argument to your app. So if you’re launching your app from the terminal you’d pass -com.apple.CoreData.SQLDebug 1 as a command line argument as usual. If you’re running from within Xcode then you set the arguments to pass to your app in the Scheme settings which you access via Edit Scheme… or Manage Schemes… + Edit Scheme….  Here’s a screenshot of the Edit Scheme sheet where you can see how to enter this flag:

Set Command Line Agrument

A Legend Awakens

February 10, 2014

“A Legend Awakens” in the Tengwar script written using a Fraktur black-letter calligraphic style, by Geek. A snow day project.

IMG_3100_web

 

 

NSURLConnection & GDC

January 9, 2014

Using NSURLConnection combined with GCD for the first time and noticed that if you invoke NSURLConnection on anything other than the main queue it seems to lock up and nothing happens.  Actually something happens but your delegate never gets called.  Easy fix though; you just need to set the delegate queue (or run loop) before starting the download.

 

Here’s some sample code setting the delegate queue for you to play with if you like. Just make a sample cocoa app from the standard template and then setup the application delegate like this


@interface AppDelegate ()
  @property (strong) NSURLConnection* connection;
  @property (strong) NSMutableData * downloadedData;
@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
  // Insert code here to initialize your application

  dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), 
   ^{  
      self.downloadedData = [NSMutableData new];
      NSURLRequest * request = [NSURLRequest requestWithURL: 
      [NSURL URLWithString: @"http://wp.me/av6Bm-pZ"]];
      self.connection = [[NSURLConnection alloc] initWithRequest: request 
                          delegate: self 
                        startImmediately: NO];  // This *must* be "NO". 
                                                // Can't switch delegate queue 
                                                // after download starts
      [self.connection setDelegateQueue: [NSOperationQueue mainQueue]];  // *** set queue
      [self.connection start];   // *now* you can start the fetch
      NSLog(@"request queued!");
   });
}

// delegate calls just so let us know when it's working or when it isn't

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog( @"download failed with an error: %@, %@", 
        error, [error description] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog( @"connection did receive response: %@", response );
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"download data received %lu", [data length] );
    [self.downloadedData appendData: data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"didFinishLoading.  total data is: %lu", [self.downloadedData length] );

    // release this stuff, test is done.
    self.connection = nil;
    self.downloadedData = nil;
}

@end

Line 22 is the key (the setDelegateQueue: call). If you leave that line out then you’ll wonder why it’s not downloading your data. If you change the queue passed to line 12 with dispatch_get_main_queue() then it’ll work without the setDelegateQueue: call).

Obvious once you see it but maybe this’ll save someone a bit of time.

P.S. This was done with Xcode 5 under 10.8.5 fwiw.

10 year old Geek explains why he does what his parents ask…

January 3, 2014

Posted this on Twitter but then realized that goes away and this is funny enough I wanted to keep it around.

IMG_2935 name obscured web

 

 

In case his 10-year-old writing is hard to read,

“I have to do what my parents tell me because they are insane and their doctor told me to humor them.”

:-P

None of us remembered this but it was found during our move and gave us all a laugh.  Creative rationalization.

 

Something I wrote back in March when trying out Draft

November 21, 2013

Late one night back in March I tried out a cloud-based editing platform that Nathan Kontny is putting together called Draft.  It’s designed to save various drafts of your writing and to facilitate getting feedback from others as you write.  I sat down and wrote one short thing and then didn’t get back to it (we packed up our farm and moved so Geek could go to college but still live at home (he’s 16) and I didn’t have time).

Today Nathan sent an email about some neat new features which prompted me to go take another look.  WOW!  He’s added a ton of interesting capabilities.  Anyway, I realized I hadn’t published the thing I wrote and while it started out as a “blank page! Yikes!” it did document some of what was happening then and some of my thoughts about the 1% (big in the news at the time) and the challenging economic times.  Since Draft doesn’t have a feature to host finished work (turns out it does: Draft SitesI thought I’d put it here so I don’t forget it:

So, it begins. Once again all thought stops when faced with a blank page. An open window through which only air and the sounds carried upon it pass. And light. And smells. Fresh spring smells and sounds.

Where exactly to begin? Do we start with the falling apart of the social fabric? Or maybe the seeming inability of a large percentage of the super wealthy to see that sucking all the money out of an economy is like sucking all the air out of a sealed space. A fatal result for those on the inside in both cases. Even good people get desperate when they can’t breath. Or don’t have enough food to feed their children.

Sent money today to a friend who’s regular weekly music gig got cancelled for good after twice being cancelled “just this weekend.” As a result he doesn’t have enough money for food despite living on bags of potatoes from CostCo which he adorns with left-over condiments from his friend who cleans vacation rentals. Said he saw a rat in his kitchen the other night and wonders if country rats carry much disease. “As a buddhist I don’t want to kill it but I’m a little scared it might carry disease and I can’t afford a visit to a doctor…” he told me.

Time to sleep so I can earn more money tomorrow.  Might get a call from another friend in need.

—-

By the way, Nathan has a lot of great stuff on his blog about all kinds of things.  I especially liked:

Why Science Fiction?

October 16, 2013

Neil Gaimon on Science Fiction:

I was in China in 2007, at the first party-approved science fiction and fantasy convention in Chinese history. And at one point I took a top official aside and asked him Why? SF had been disapproved of for a long time. What had changed?

It’s simple, he told me. The Chinese were brilliant at making things if other people brought them the plans. But they did not innovate and they did not invent. They did not imagine. So they sent a delegation to the US, to Apple, to Microsoft, to Google, and they asked the people there who were inventing the future about themselves. And they found that all of them had read science fiction when they were boys or girls.

So, maybe encourage a little Science Fiction in your child’s menu of reading material.

I probably don’t have to say this, but introduce your daughters to science fiction also. There are some great female science fiction authors  and there’s another list here.  Dad finds that female authors seem to be a lot more likely to include strong & smart female characters that have depth and are thus more interesting.  Peace.


Follow

Get every new post delivered to your Inbox.

Join 1,166 other followers