Challenge solutions - I think I get it now!


Okay so I re-read this chapter and looked here for more explanation on how blocks are useful - it was only until I completed the NotificationCentre challenge that it was clear to me…

I was still thinking that we could / do use blocks in separate bits of code for example: In the NSNotificationCentre - before I looked at the Apple documentation I was saying to myself I might do it like this:

[[NSNotificationCenter defaultCenter] addObserverForName:NSSystemTimeZoneDidChangeNotification object:nil queue:nil usingBlock:^(BLOCK NAME)];

Then writing out the code for the block name elsewhere in the code - which begged the questions: 1. What’s the point and 2. How is this different to the last version when I used a method to run my Notification centre, which was else where.

So I came up with the solution like this:

[[NSNotificationCenter defaultCenter] addObserverForName:NSSystemTimeZoneDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification *note){ NSLog (@"Time zone changed!"); }];

How flipping awesome is that!!? :smiley: :smiley:

  1. It works!
  2. Its now clear what this line of code does and its all in one place!

I suspect blocks are more powerful than just coupling the code for readability - I’m use the more I use it the better / clearer it will become to me.

With the first challenge this is what I came up with:

[code] [oldStrings enumerateObjectsUsingBlock: ^(id string, NSUInteger i, BOOL *stop){

        NSRange yRange = [string rangeOfString:@"y" options:NSCaseInsensitiveSearch];

            //Did I find why?

        if (yRange.location !=NSNotFound){
            *stop = YES; //Stop the iteration

            return; //Stop this iteration 

        NSMutableString *newString = [NSMutableString stringWithString:string];

            //Iterate over the array with vowels, replacing each occurance with an empty string

        for (NSString *s in vowels){

            NSRange fullRange = NSMakeRange(0, [newString length]);

            [newString replaceOccurrencesOfString:s

        [newStrings addObject:newString]; 

    }]; //End of block assignment      


This way - I haven’t given the block a name - it’s used anonymously. Pretty cool. :sunglasses:

So I will take Mike’s advice and use the block version of in more of Apple’s methods when they are available.


Thank you so much for the solution of the first challenge. I was thinking the whole day how i can anonymous use a block variable. Now i get it.