Tag Archives: Blocks

Architecting with Blocks part 2

(Note: This is part 2 of a series of posts about Architecting an application using blocks in objective-c. By no means I am an expert on using blocks, and also it’s not the intention of this series to teach you how to use blocks. You can check this for that. To finalise, I am sure there are better ways to use blocks while architecting an app: use this at your own risk. :))

This is the final post from a 2 parts series that I start a long ago. In this case I won’t show any snippet of code, I will give away an entire sample. My approach about this matter, change in the meantime, nonetheless hope you enjoy it. You can find it here .

Tagged , , , , , , ,

Item 1, Familiarize Yourself with Objective-C’s Roots

Note: This post is part 1 of a series of posts I will do about the new book of Matt Galloway.

Familiarize Yourself with Objective-C’s Roots

Dynamic language

In this item, the author starts by delving into how Objective-c send messages as opposed of function calling (in this case comparing to C++)  and when one should be used instead of the other (you can still use function calling in objective-c).  The dynamic nature of objective-c, binds the messaging to the corresponding piece of code that will be called, at runtime; as opposed to C++ (for example) that is done at compile time.

Memory Management

One should understand how related objective-c is to c (it’s a superset) and how/where the allocations are made:

NSString *aString = @"BlahBlah";

In this case “aString” is a pointer to a piece of memory allocated on the heap. Although this is mostly true for allocating objects in objective-c, blocks for example are allocated on the stack, but can be  passed to the heap (block_copy()).  An excellent post by Mike Ashe explains this as well.  Plus when you alloc, new, retain or copy an object, you are responsible for them.  It’s important as well to know how the memory is managed in objective-c:

 ” (..) that any single object can have multiple “owners”, and the system won’t allow the object to be destroyed until all owners have relinquished ownership.” – Mike Ashe,  Stack and Heap Objects in Objective-C

In one hand with manual memory management, you are responsible for cleaning the house, with ARC the cleanup is being made for you. Do remember, that ARC is not a Garbage collector, so you should need to understand when you have to do something (circular references for example) and when you don’t.

You will find plenty of variables that will be create on the stack, for example:

CGPoint point = CGPointMake(12.0f,10.0f);

CGPoint is a structure and it’s defined like this on CGGeometry.h from CoreGraphycs.framework:

struct CGPoint {

CGFloat x;

CGFloat y;

};
typedef struct CGPoint CGPoint;

It’s important to measure if you are going to use objects (vars that point to something that has being allocated on the heap) and, in this case, structures (vars that might be using stack space), or non-objects int,float, char, etc. Allocating objects  can incur on an unnecessary overhead, so chose the right tool for the job in hand.

The first item, is a very well written intro into how objective-c works internally versus other languages, and how you can take advantage of the C language . As it is build upon it, some time should be taken to understand it.

Tagged , , , , , , ,

Blocks as Closures

Closures can be something difficult to grasp but they have some interesting use-cases from simple to harder ones. For instance:

def power_to
  foo = 1
  Proc.new { foo += foo }
end

proc_obj = power_to
puts proc_obj.call
puts proc_obj.call
puts proc_obj.call

This will print:

$ 2
$ 4
$ 8

The method power_to returns a Proc object which has the state of foo local variable. Though, the variable remains accessible to the block even if that variable is out of scope when the block is called again.

That’s closures and it’s the basis of lexical scoping which you can find in other programming languages such as JavaScript.

Tagged , , ,

Pointer to a Pointer

I came to a point (the irony…) where I needed the following:


// Declare the queue
dispatch_queue_t workingQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(workingQueue,
^{

NSError *parsingError = nil;

if (condition == YES)
{
    [self doSomethingLongWithError:&parsingError];
}
else
{
    [self doSomethingElseLongWithError:&parsingError];
}

dispatch_async(dispatch_get_main_queue(), ^{

// Check if we got an error

if (parsingError)
{
    error(parsingError);
}
else
{
    success();
}
});
});
}

So what’s happening?

– I have one working thread doing some heavy stuff (in this case parsing)
– Once that work is done I want to update my UIViewController, by executing the block success() or the block error(parsingError).

The idea here is to be able to actually do something heavy, not expecting a return, and also be able to know if something went wrong.

As you might imagine the signature of the methods is:

- (void)doSomethingLongWithError:(NSError **)error;
- (void)doSomethingElseLongWithError:(NSError **)error;

If you notice, I am passing an &parsingError in both methods. Why? Well that’s where it becomes interesting the use of pointers to pointers. The powerful aspect of it is that I am able to declare the parsingError on the scope of the working thread, pass it’s pointer to a different scope (in this case of the methods) and once that working thread is done I can rely on the value of the parsingError on the main thread to take the appropriate action.

Tagged , , , , , , ,

Architecting with Blocks part 1

(Note: This is part 1 of a series of posts about Architecting an application using blocks in objective-c. By no means I am an expert on using blocks, and also it’s not the intention of this series to teach you how to use blocks. You can check this for that. To finalise, I am sure there are better ways to use blocks while architecting an app: use this at your own risk. :))

On most of the applications out there ( I would say 60%, not counting with games), a normal application follows the same pattern:

  •  Server Request
  •  Handle Response
  •  Parse it
  •  Show to the user
  • Handle any error that might appear

What I have been using, so far, to handle this typical problem is:

  • ViewController complying to a protocol
  • Pass reference to the Server Requester Class (normally like this @property(weak,nonatomic) id <myProtocol> delegate)
  • Request Data
  • Take care of data (Parsing usually)
  • Using the reference passed before, call the most appropriate method from the protocol (normally either success or failure)

It’s the usual pattern, but it can become a bit verbose, if you happen to have a lot of different UIViewControllers, requesting and expecting different things. So, on my last project I tried to rely mostly on blocks.

I had three different kind of resources to get from the server, one of them would rely on the other two (to make the 3rd request I would need that the user had choose the other two). I started by creating a typedef enum:

// Used to know which request we are using
typedef enum
{
kFirstRequest,

kSecondRequest,

kFinalRequest

} kRequest;

You use the typedef enum so you can better understand your code ( kFirstRequest, kSecondRequest and kFinalRequest are nothing more than integrals). Next, you define four blocks:

// Block that will be executed when the server's response has been received and parsed
// In theory, you won't need the typeOfRequest to be passed to the block, but you can use it as well
typedef void(^SuccessBlock)(NSArray *arrayObjects, kRequest typeOfRequest);

// Block that will be executed when we receive the server's response
typedef void(^ParsingBlock)(NSData *serverResponse);

// Block that will be executed if something goes wrong (Request, or Parsing)
typedef void(^ErrorBlock)(NSError *errorObject);

// Block that will be executed if something goes wrong (Request, or Parsing)
typedef void(^RequestBlock)(NSError *errorObject, kRequest typeOfRequest);

This is the base of our code. Instead of using a protocol and pass references between different objects, we will pass blocks. You should add this code to a file called Constants.h. On your prefix.pch file, you should import it. This way, you have access to the blocks and the typedef enum in any part of your application.

Tagged , , , , , , , , ,

Sorting results from CoreData Fetch

In this case, you want to compare a CLLocation from the user to the lat & long you have on your CoreData:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *entity = [NSEntityDescription entityForName:ENTITY_NAME inManagedObjectContext:self.managedObjectContext]

[fetchRequest setEntity:entity];

NSArray *arrayOfEntities = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];

arrayOfEntities = [arrayOfEntities sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(id obj1, id obj2)
{
    CLLocation *obj1EntityLocation = [[CLLocation alloc] initWithLatitude:[(NSNumber*)[obj1 valueForKey:ENTITY_LAT_KEY] doubleValue]longitude:[(NSNumber*)[obj1 valueForKey:ENTITY_LONG_KEY] doubleValue]];

    CLLocation *obj2EntityLocation = [[CLLocation alloc] initWithLatitude:[(NSNumber*)[obj2 valueForKey:ENTITY_LAT_KEY] doubleValue]longitude:[(NSNumber*)[obj2 valueForKey:ENTITY_LONG_KEY] doubleValue]];

    CLLocationDistance dist1 = [obj1EntityLocation distanceFromLocation:userLocation];
    CLLocationDistance dist2 = [obj2EntityLocation distanceFromLocation:userLocation];

    return [[NSNumber numberWithDouble:dist1] compare:[NSNumber numberWithDouble:dist2]];
}];

return arrayOfEntities;
}

The point is to be able to sort an array that comes from CoreData in a nonlinear way, by using Blocks.

Tagged , , , , , , , , , ,