Categories
Apple iOS Mac

Future macOS Frameworks

Duct Tape, fixer of all things!I stumbled upon an interesting conversation between some well know Apple Ecosystem Developers this morning discussing, maybe lamenting, the lack of UIKit on macOS. I’m afraid I may have pushed these fellas to take their conversation private, I am sorry if that was the case.

Here’s the tweet that started the conversation:

https://twitter.com/stroughtonsmith/status/779726806727491584

I’m not known in any development communities. I’m what you’d call a nobody. But I’m a nobody with years of experience that has seen changes to my development ecosystem.

Having experienced a dramatic shift in Windows Development technologies I have opinions about what I would expect to see from Apple. These opinions and $10.00 should be enough to buy you any item on a Starbucks drink menu. Take if for what it is. An opinion of a nobody.

What I Expect

Given Apple’s love and focus on Swift I fully expect Apple to put their effort into moving their frameworks to focus on Swift while continuing to allow App developers to use Objective-C with anything new. I’ve written about the idea of Swift only Frameworks. I believe we will eventually arrive there. For now we have excellent UIKit support for three different devices; iOS, watchOS, and tvOS. Odd man out would be macOS. It doesn’t make sense, at least to me, for Apple to spend time back porting or adapting UIKit to the Mac. Their bread and butter is their  iOS based trio of the phone, watch, and cable like device. Since iPhone accounts for around 60% of revenue it makes sense for the iOS Platform to be their primary focus. That begs the question, will the Mac ever receive the attention we’d like it to receive? Probably not.

In the end I’d expect Apple to push iOS forward while keeping the Mac as a primary development system for iOS, watchOS, tvOS, and macOS developers with the latter receiving very little attention from a new Frameworks perspective.

A Brief History of Windows Development

Like I said above, I’m opinionated and I’ve been around the block a few times. I know Apple isn’t Microsoft and people tend to hate those comparisons. But I do see similarities between the Microsoft of the 90’s and the Apple of today. That’s a discussion for another time.

The discussions around Frameworks reminds me of Microsoft’s transition to .Net and C# as an easier way for developers to create Windows Apps. Apple is making such a big push with Swift a new framework targeting Swift developers feels like a natural progression.

It’s taken over 15-years to really push app development into a .Net world. I suppose some could argue it took less than 10 and I wouldn’t fight that. The point is Microsoft managed to push an entire development community to a new technology while allow old technologies to continue to not only function but grow. Look at the Microsoft Office Apps and Adobe Photoshop among others. They continue to be very relevant today and continue to add new features while the Windows API receives much less attention than does .Net and C#.

Ultimately the point is I know Apple could choose to push toward a Swift only framework and allow legacy Objective-C/Cocoa apps to continue to grow and thrive. Microsoft is a prime example of how a company could pull it off.

I think it’s kind of nice being a new developer to Apple’s platforms. I don’t have 20+ years of baggage like I do with Windows. It’s been so much easier to move from Objective-C to Swift because of it. Well, that and being most familiar with C++ made the transition to Swift feel more natural to me.

Whatever Apple has in store for us, be it the growth of Cocoa, a new Swift centered framework, or a Swift only framework, I’m ready for it and welcome it.

Categories
Development

Revisiting Objective-C, REST, and JSON

I get a lot of hits on this site for two posts.

  1. Objective-C REST and JSON
  2. Objective-C Objects from JSON

Both posts touch on using JSON to create Objective-C objects. The first one mostly talks about great Cocoa Libraries you can use to make REST calls and parse JSON results.

Since that time JSON parsing has become a part of iOS. In iOS 5 Apple introduced NSJSONSerialization.

For a presentation on REST and JSON to @NSSLO back in May I created a super simple project that used NSURL, NSMutableURLRequest, NSURLConnection, and NSJSONSerialization to call the iFixIt API.

If you’re interested in grabbing the project, it’s available on GitHub.

Will write C/C++ for food

The Code

Most of the RESTTest project is a boiler plate iOS application. There are a couple places in MasterViewController.m you should pay attention to and we’ll take a look at the iFixItBadges and the iFixItBadge classes.

The Basics

To get the ball rolling we make a call to a private method: getBadges.

- (void)getBadges; {
	NSURL *url = [NSURL URLWithString:@"http://www.ifixit.com/api/0.1/badges"];
	NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData 
                                                       timeoutInterval:10];
	if (request) {
		[request setURL:url];
		connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	}
}

This method is pretty straight forward and uses three of the four classes we mentioned above; NSURL, NSMutableURLRequest, and NSURLConnection. That’s all it takes to do a simple(REST) HTTP GET call. Yes, it’s sample code, so it’s not complex and is not something you’d find in a shipping application as is. It would need some beefing up and it definitely changes if you’re going to do a POST, or DELETE call, not to mention the lack of authentication. I picked the badges call because it didn’t require authentication.

When we allocate and initialize NSURLConnection it takes off and starts doing the work. Notice we’ve specified self as the delegate, which means NSURLConnection will expect us to have implemented the NSURLConnectionDelegate Protocol.

The next method we’ll want to take a look at is connectionDidFinishLoading.

- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	NSString* s = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
	NSLog(@"Received data %@", s);

    badges = [[IFixItBadges alloc] initWithData:receivedData];
    
    [self.tableView reloadData];
}

This is called by NSURLConnection when it’s finished receiving the response from our badges call. At this point we should have a nice JSON response to parse. Notice we’re working on receivedData, which is private and is built in the didReceiveData method. I’d recommend building the code and running it in the debugger to see how it works.

Back to connectionDidFinishLoading. We have our receivedData (an NSMutableData*), now we’re going to create an IFixItBadges object.

Creating objects from JSON

To review. We’ve called the iFixIt badges method and we’ve received our response data. Now we need to do something with it. Say hello to NSJSONSerialization.

- (id)initWithData:(NSData*)data;
{
    if ((self = [super init])) {
        badges = [[NSMutableArray alloc] init];
        
        NSError *error = nil;
        NSArray *resultData = [NSJSONSerialization JSONObjectWithData:data
                                                              options:kNilOptions
                                                                error:&error];
        if (resultData && nil == error && badges) {
            NSDictionary *badgesData = nil;
            NSEnumerator *resultsEnum = [resultData objectEnumerator];
            while (badgesData = [resultsEnum nextObject]) {
                IFixitBadge *badge = [[IFixitBadge alloc] initWithDictionary:badgesData];
                [badges addObject:badge];
            }
        }
    }
    
    return self;
}}

When we get our result back we create an iFixItBadges object, which is a collection of iFixItBadge objects. We could’ve just as easily used NSMutableDictionary or NSMutableArray to hold these objects.

Notice the use of NSJSONSerialization. One call. That’s all it takes to create an array of data we can then iterate over to create an iFixItBadge to add to our collection. Once the collection is created we tell the table view to reload itself using [self.tableView reloadData];

That’s it in a nutshell. If you have any questions about this, or find a problem, please feel free to leave a comment or send email to rob.fahrni@gmail.com.

Happy coding.

Categories
Development

Objective-C Objects from JSON

I was asked recently how to create an Objective-C Object from a JSON result returned by a RESTful service. Man, that’s a mouthful.

It’s actually fairly easy, especially if you make use of the excellent JSONKit by John Engelhart. The example below does just that.

For starters I created a simple Cocoa Application and changed main() so it returns 0, because we don’t need to show a window and have an event loop. Here’s a link to the complete main.m.

Next add JSONKit.m and JSONKit.h to your project, and build. That’s it. It should just work.

Here’s what the code does.

For starters we define some sample JSON. This is very rudimentary. The object contains a firstName and lastName field. This is meant to represent the data returned by our pretend REST service.

static NSString* const kSampleJSON = @"{\"firstName\": \"Rob\", \"lastName\": \"Fahrni\"}";

Next up we define a Person interface.

@interface Person : 
    NSObject
{
@private
    NSString* _firstName;
    NSString* _lastName;
}

@property (copy) NSString* firstName;
@property (copy) NSString* lastName;

- (id)initWithDictionary:(NSDictionary*)dict;
- (void)dealloc;

@end

Again, very simple. This Person interface has first name(_firstName) and last name(_lastName) members and is initialized by passing it an NSDictionary*. So far, it looks pretty easy, right? Right!

The next thing we need to do is implement Person. Once again, no rocket science here. It’s straight Objective-C.

@implementation Person

@synthesize firstName = _firstName;
@synthesize lastName = _lastName;

- (id)initWithDictionary:(NSDictionary *)dict;
{
    if ((self = [super init]))
    {
        _firstName  = [dict valueForKey:@"firstName"];
        _lastName   = [dict valueForKey:@"lastName"];
    }
    
    return self;
}

- (void)dealloc;
{
    [_lastName release];
    [_firstName release];
    
    [super dealloc];
}

- (NSString*)description
{
    // Overriding description allows you to print something meaningful
    // to the debug output window. In this case we'll print 
    // Rob Fahrni.
    return [NSString stringWithFormat:@"%@ %@\n", _firstName, _lastName];
}

@end

Ah! Now we’re getting somewhere. Notice the Person is constructed with an NSDictionary* that should contain at least two entries; firstName and lastName. Note “firstName” and “lastName” just so happen to match our simple JSON constant, defined as kSampleJSON. That’s because it’s the source of our data.

Something else of note is the method description. By overriding NSObject description we allow NSLog to dump something meaningful when we give an instance of Person as an argument. You’ll see that used below. It’s darned handy when you’re debugging.

UPDATE 12/31/2011: I noticed I’d used objectForKey instead of valueForKey when assigning to _firstName and _lastName.

Finally we can test our code to see what it does.

int main(int argc, char *argv[])
{
    // Pretend like you've called a REST service here and it returns a string.
    // We'll just create a string from the sample json constant at the top
    // of this file.
    NSString* responseJSON = [NSString stringWithFormat:@"%@", kSampleJSON];
    
    // 1) Create a dictionary, from the result string,
    // using JSONKit's NSString category; objectFromJSONString.
    NSDictionary* dict = [responseJSON objectFromJSONString];
    
    // 2) Dump the dictionary to the debug console.
    NSLog(@"Dictionary => %@\n", dict); 
    
    // 3) Now, let's create a Person object from the dictionary.
    Person* person = [[[Person alloc] initWithDictionary:dict] autorelease];
   
    // 4) Dump the contents of the person object
    // to the debug console.
    NSLog(@"Person => %@\n", person);

    return 0;
}

That’s all there is to it? Yep, that’s it! Pretty simple, right?

Categories
Development

Mike Ash on Objective-C Blocks

Duct Tape, fixer of all things!Mike Ash: “Both Objective-C blocks and C++0x lambdas have the same basic goal: to allow writing anonymous inline functions. Called closures, blocks, lambdas, or just anonymous functions, these are a common feature in higher level languages. They are extremely useful for building convenient, succinct libraries for things like array iteration, multithreading, delayed computation, and many others.”

Mike explores Objective-C Blocks and C++ Lambdas. This article is six months old, but it’s still very relevant and great as always. If you’re a Cocoa Head you should definitely add Mike’s RSS feed to your preferred news reader.

Categories
Development iOS Mac

Fresh Code: RFRddMe

Earlier this week Dave Winer pointed out some neat stuff Readability was up to. Part of the piece pointed out a new URL shortener. I marked it and came back to it today. Since I love writing code to talk to RESTful web services, why not write another one?

The Red Readability CouchThis afternoon I started on RFRddMe, an Objective-C library for the Readability Shortener Service. Late this afternoon I completed the library, and I checked it into my GitHub Repository tonight. Figuring out git submodules took a bit of time, but it works as advertised.

If you just happen to be looking for Objective-C code to shorten a URL, and add an article to Readability, look no further.

Get the code for RFRddMe on GitHub.

Please, drop me a line, rob.fahrni@gmail.com, if you use the code.

Enjoy.

Categories
Development

Objective-C REST and JSON

Bringing in the HarvestThe first REST based code I wrote for the Mac and iOS was my P8 Library for ping.fm. That code is all NSRequest based and I learned a lot while doing it. Since that time I’ve done a couple more projects that consumed REST Services and XML or JASON.

To that end I thought I’d record some of the libraries I’ve run across. Some I’ve used, others are a curiosity.

REST Libraries

ASIHTTP – I’ve used this library a couple of times and I’m using it on a new project. I like it, but the developer that lovingly created it is giving up on it because people gave him too much crap. That’s a real shame, not only that he’s done with it, but that people would harass him so much he gave up on a very handy piece of code.

LRResty – A simple REST/HTTP client. Apparently this library was inspired by a Ruby implementation. I’m fairly certain this is the library I’ll be moving to this in the future.

RestKit – This library not only deals with retrieving data, it will also map it into Core Data. Pretty cool, and if you have need to cache data locally it would be worth looking at.

JSON

SBJson – A very nice JSON parser. It’s simple to use and includes handy categories for NSString and NSDictionary. It’s very simple to create a parser and operate on the results, just like you would an NSDictionary.

SBJsonParser* jsonParser = [[SBJsonParser new] autorelease];
id jsonObject = [jsonParser objectWithString:jsonString];

JSONKit – This is a parser I only recently discovered, and it’s known to be fast and efficient. It’s also super easy to use because of, you guessed it, categories. There’s a real nice one added to NSString.

NSDictionary* response = 
[[request responseString] objectFromJSONString];

See how easy that is to use? You simply invoke objectFromJSONString to get a fully parsed result jammed into an NSDictionary.

Categories
Apple Development Objective-C

ARC

ARCMike Ash: “That, in essence, is what ARC is. The memory management rules are baked into the compiler, but instead of using them to help the programmer find mistakes, it simply inserts the necessary calls on its own.”

Reference counting is a pain in the keister, until you understand the rules. ARC is going to become an important tool in the quest to creating error free code. If you’ve ever written ref counted code you know how careful you need to be so you don’t leak memory or double-release something and cause a crash. It can be frustrating if you don’t pay attention.

This is a welcome change and one I’m looking forward to.

I think it’s time for an RxCalc refresh anyway. Plus some other nifty things I’ve been working on, that will definitely be ARC’d and Mac OS X Lion / iOS 5 only.

Categories
Development

Testing Undo

Gus Mueller: “The idea being that I call multiple operations in quick succession (from JSTalk) and then test each of those undos and make sure the state is exactly what it should be. I recently came across an instance where I needed to do the same thing in Objective-C code, so I thought I’d share with my fair readers the solution I came up with (experienced Obj-C coders will probably know right away what the solution is).”

AKA – Fun with blocks.

Categories
Development

Objective-C Memory Management, The Rules

Objective-C Ref CountingInterfacelab.com: “There are only 4 basic rules when it comes to memory management in Objective-C:

If you own it, release it.
If you don’t own it, don’t release it.
Override dealloc in your classes to release the fields that you own.
Never call dealloc directly.

That’s it. The first two are the most important and we’ll get into the basics of object ownership next.”

Just an FYI for those coming from another platform, or language. Remember, Objective-C’s parent is plain ole C, and you can mix C and C++ with your Objective-C. Keep the alloc/free, new/delete rules in mind when allocating objects. Also remember Objective-C objects are reference counted objects. If you want to keep an object around bump its retain count by doing…

anObject = [object retain];

When you’re done make sure you do

[object release];

Otherwise you’ll have a leak in your code.

I’d recommend a quick look at Cocoa Dev Central’s Learn Objective-C tutorial. It’s very good.

Once you have the rules figured out it’s fairly straight forward.

Categories
Development Uncategorized

Using P8, the ping.fm Objective-C engine

I just wanted to test a code highlighter plugin for WordPress, so I’ll use my open source ping.fm Objective-C engine as an example. Yeah, I know, shameless self promotion.

Here’s how to use P8 in your app…

[codesyntax lang=”objc”]

// Yes, you owe a Release later for P8 and
// TestDelegate. This example doesn't do it.
TestDelegate* del = [[TestDelegate alloc] init];
P8Engine* P8 = [[P8Engine alloc] initWithOptions:kP8APIKey appKey:kP8AppKey delegate:del];
if (nil != P8)
{
	// Post something.
	[P8 userPostStatus:@"Testing 1,2,3... Please ignore, http://f67.us/iam"];

	// Create a short URL
	[P8 urlCreate:@"http://rob.crabapples.net/"];

	// Resolve a short URL
	[P8 urlResolve:@"http://ping.fm/xeECl"];
}

[/codesyntax]

Ok, I don’t really like that.