Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing my own block method

I am trying to follow through examples from other as well as Apple. I'm lost.

I have a singleton class that I use to handle my user logging in (challenges a web server, etc.).

I want to create a block I can call, pass in the username/password. The block will perform the web service calls then return if it was successful or not.

This is what i've manage to get working so far:

My singleton class looks like this:

.h

typedef void (^AMLoginBlock)(NSString *userName, NSString *password);

@interface AuthManager : NSObject
+ (id)sharedManager;

+ (bool)loginUserWithBlock:(AMLoginBlock)block;

@end

.m

@implementation AuthManager

+ (id)sharedManager
{
    static dispatch_once_t pred = 0;
    __strong static id _sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; // or some other init method
    });
    return _sharedObject;
}

+ (bool)loginUserWithBlock:(AMLoginBlock)block {
    NSLog(@"im printing from AM");
    return true;
}

@end

I then call the method like so:

bool rtn = [AuthManager loginUserWithBlock:^(NSString *userName, NSString *password) {
        NSLog(@"im here in the block LVC.");
    }];

My question is three parts:

  1. How do I write a completion handler for the block similar to UIView animation... block.

  2. Is it a good idea to perform these web service calls from a block based implementation?

  3. Should I be declaring the block method like so:

    - (bool)loginUserWithBlock:(AMLoginBlock)block;

instead of using +(bool)loginUser.. since it is in a singleton class. Not sure if this will cause multiple instances of the singleton to be created.

My goal is to be able to call this block like you call [UIView animation..]. So I can simply do:

[AuthManager loginUserWithUsername:foo
                          password:bar1
                        completion:^(BOOL finished) {
                            if (finished)
                                //push new view controller.
                            else
                                //spit out error
                   }];
like image 256
random Avatar asked Sep 13 '12 04:09

random


People also ask

How do you write a block method?

The block method works best on short papers about simple topics. To do the block method, first write an introduction. In the introduction, draw the reader's attention, give background information, state the two things being compared and contrasted, and provide a thesis statement.

How do you write a block format for an essay?

In block format, the entire text is left aligned and single spaced. The exception to the single spacing is a double space between paragraphs (instead of indents for paragraphs).

How many paragraphs are in a block method?

Block Organization in Four Paragraphs Introduction: Get your reader's attention and state your purpose which is to discuss the differences between A and B. II. Topic A, (1) ______, (2) ________, and (3) ________.

What is block arrangement in writing?

In a block arrangement the body paragraphs are organised according to the objects. The block arrangement discusses one of the objects in the first body paragraph and the other object in the second. All the ideas provided in the first paragraph are also provided in the second paragraph in the same order.


1 Answers

Completion Handler

You will want to copy the completion block to a class iVar:

@property (nonatomic, copy) void (^completionHandler)(bool *);

Because you are saving the block, you need to have a non-class method take the block (see following for how to do this without violating your singleton). An example of your method could be:

- (void)loginUserWithUsername:(NSString *)username 
                     password:(NSString *)password 
                   completion:(void(^)(bool *finished))completionBlock
{
    // Copy the blocks to use later
    self.completionHandler = completionBlock;

    // Run code
    [self doOtherThings];
}

Then when your login code has finished its work, you can call the block - here I pass self.error, a bool to the block :

- (void)finishThingsUp
{
    // We are done with all that hard work. Lets call the block!
    self.completionHandler(self.error);

    // Clean up the blocks
    self.completionHandler = nil;
}

Good Idea

Well, this is a philosophical question, but I will say this: Blocks in Objective-C allow you to write code that performs a single task and easily integrate it into many programs. If you chose to not use a completion handler in your login code you would need your login code to:

  • Require that classes using it implement a protocol (as in a LoginDelegate)
  • Use some other system of informing your code such as Key Value observing or Notifications
  • Hard code it to only work with one type of calling class

Any of the above approaches are fine, I feel a block-based call back system is the simplest and most flexible. It allows you to just use your class without worrying about additional infrastructure (setting up notifications, conforming to protocols, etc. ) while still letting you reuse it in other classes or programs.

Singelton

Methods that begin with a + in Objective-C are class methods. You cannot use class methods to manipulate iVars, as who would own that data?

What you can do is have a class method that always returns the same instance of that class, allowing you to have an object that can own data, but avoid ever having more than one of them.

This excellent Stack Overflow answer has sample code.

Good Luck!

like image 62
redlightbulb Avatar answered Oct 12 '22 20:10

redlightbulb