문제

I have this method with a block in it, I want it to send the userID to another method as soon as it exists. userID is a value that is parsed from the internet, so it usually takes about 2 seconds to load up and 'exist'. Is there any way I can do a 'when userID exists, send it to another method?
Here's all my code:

- (void)parseForUserID {
    //Get the Data you need to parse for (i.e. user main page returned as a block of NSData.
    TClient *client = [[TClient alloc] init];
    [client loginToMistarWithPin:@"20014204" password:@"yuiop" success:^{
        [client getUserID:^(NSString *result) {
            NSString *userIDWithHTML = [self userIDRegex:result];
            NSString *userID = [self onlyNumbersRegex:userIDWithHTML];

            //if userID exists, send it to another method in a different class

        }];
    } failure:^{
        NSLog(@"login failed from controller");
    }];
}
도움이 되었습니까?

해결책

I see that this is the third question you ask related to the same issue, so I guess you're having some trouble understanding blocks.

First you have to understand that the block, in a certain sense, can be seen as a function. The difference is that, unlike a function, the block has no name, and instead of using function's name you just place the code inline where you need it.

Second thing to understand is that a block is usually used as a callback. Other callback mechanisms are function pointers and delegates. When you pass a block as a parameter to a function you're basically telling the function: "Hey, when certain conditions are met, execute this little code for me, please"

Third think to understand is if the block (or any callback) will be called synchronously. Actually this has nothing to do with the block itself, per se, but rather with the function being called. If the function is asynchronous, the function will create another thread and return immediately to execute the next line after the one that invoked the asynchronous function. Meanwhile the new thread will execute some code (the body of the async function) and, eventually execute the block passed as parameter, and finally the thread is killed and doesn't exist any more. (Note: There's no way to know if a function is synchronous or asynchronous other that reading the documentation for such a function).

Now let's go back to your code.

[client loginToMistarWithPin:@"20014204" password:@"yuiop" success:^{
    [client getUserID:^(NSString *result) {
        NSString *userIDWithHTML = [self userIDRegex:result];
        NSString *userID = [self onlyNumbersRegex:userIDWithHTML];

        // PLACE HERE THE CODE TO EXECUTE WHEN SUCCESSFULLY LOGGED IN
        [anotherClassInstance someMethod:userID];

    }];
} failure:^{
    NSLog(@"login failed from controller");
}];

Everything that should be executed once the user logged in should be placed inside the block (if the function is synchronous you could place it after the block). To send the userID to another class, just call that class' method as you would in any other part of your code.

In my opinion using a delegate is not necessary (although only you would know, since you're the architect of your app).

다른 팁

As @santhu said, use either the delegate pattern or notification pattern. It's also a common practice to use both of them. Usually a delegate is the correct approach but sometimes you need a notification. Using both covers all your bases.

Look them up before deciding which and for full details on how they work, but basically:

[client getUserID:^(NSString *result) {
    NSString *userIDWithHTML = [self userIDRegex:result];
    NSString *userID = [self onlyNumbersRegex:userIDWithHTML];

    // delegate pattern:
    if ([self userIdIsValid:userID]) {
      if (self.delegate && [self.delegate respondsToSelector:@selector(foundValidUserID:)]) {
        [self.delegate foundValidUserID:userID];
      }
    } else {
      if (self.delegate && [self.delegate respondsToSelector:@selector(foundInvalidUserID:)]) {
        [self.delegate foundInvalidUserID:userID];
      }
    }

    // notification pattern:
    if ([self userIdIsValid:userID]) {
      [[NSNotificationCenter defaultCenter] postNotificationName:MyFoundValidUserIDNotification object:self userInfo:@{@"userID": userID}];
      }
    } else {
      [[NSNotificationCenter defaultCenter] postNotificationName:MyFoundInvalidUserIDNotification object:self userInfo:@{@"userID": userID}];
    }


}];

There is a third option, which is you could use a block callback... this is how the new kids on the block do it... there's no well defined pattern here, blocks are brand new and delegates/notifications are 20 years old. But here's how I'd use a block to define a callback:

typedef void (^UserIdCallbackBlock)(NSString *userID);

- (void)parseForUserIDOnSuccess:(UserIdCallbackBlock)successCallback onFailure:(UserIdCallbackBlock)failureCallback {
  ...

  NSString *userID = [self onlyNumbersRegex:userIDWithHTML];

  if ([self userIdIsValid:userID]) {
    successCallback(userID);
  } else {
    failureCallback(userID);
  }

  ...
}

I would like to give a hint regarding your comment:

for code readability, it's not that I just have one more task to do, the thing I put inside this block will also have a block and another block and another.

This is a typical asynchronous pattern - called "continuation".

Given, that you should also implement proper error handling and that you should also provide a means to cancel that whole "chain" of asynchronous tasks at any point, the typical solutions with NSOperationQueues and NSOperations, dispatch_queue and blocks, NSNotifications or delegates will inevitable become unduly elaborate, complex and difficult to comprehend by others. (There's already an answer here that demonstrates this grandiose ;) )

So, whenever problems become more complex and the "built-in frameworks" don't provide a comfortable solution, third party libraries come into play to help you.

But first, lets have a non-trivial example, based on your comment:

it's not that I just have one more task to do, the thing I put inside this block will also have a block and another block and another

OK, lets suppose your objective is actually:

  1. Asynchronously perform a Login for a web service.
  2. Then, if that succeeded, asynchronously fetch a list of objects as JSON.
  3. Then, if that succeeded, parse the JSON response.
  4. Then, if that succeeded, insert the objects into a managed object context and asynchronously save the chain of managed object contexts and make it persistent.
  5. When this all above succeeded, update the UI on the main thread
  6. If anything fails, report the error of the task that failed

I will show how a solution utilizing a library implementing "promises" (see wiki Future and promises) may look like:

Without further ado, and without thorough explanation what that "Promise" is about, suppose we have a method defined in your View Controller, which is declared:

- (RXPromise*) loginToMistarWithPin:(NSString*)pin 
                           password:(NSString*)password;  

Note: The above method is asynchronous and it is functional equivalent to the form:

        typedef void (^completion_t)(id result, NSError*error);
        - (void) loginToMistarWithPin:(NSString*)pin 
                             password:(NSString*)password 
                           completion:(completion_t)completion;

then suppose we have another method in your View Controller, fetching objects from a remote server (asynchronous as well):

- (RXPromise*) fetchObjects;

Then, suppose we have a class CoreDataStack which consists of a "root context" saving to the persistent store having a child managed object context, the "main context", which is associated to the main thread.

The class CoreDataStack defines this method, which saves a chain of managed object contexts, which is basically setup: childContext -> main_context -> root_context:

- (RXPromise*) saveWithChildContext:(NSManagedObjectContext*)childContext;

Then, the whole task as stated in the steps 1. through 5. can be expressed as follows:

[client loginToMistarWithPin:@"20014204" password:@"yuiop"]
.then(^id(id result){
    // login succeed, ignore result which is @"OK"

    // Now fetch the objects with an asynchronous network request, 
    // returning JSON data as a NSData object when it succeeds:
    return [client fetchAllUsers];
}, nil)
.then(^id(NSData* json){
    // The network request succeeded, and we obtain the JSON as NSData.
    // Parse it and get a Foundation representation:
    NSError* error;
    id jsonArray = [NSJSONSerialization JSONObjectWithData:json 
                                                   options:0 
                                                     error:&error];
    if (jsonArray) {
        return jsonArray;  // handler succeeded
    }
    else {
        return error;      // handler failed
    }        
}) 
.then(^id(NSArray* objects){
    // Parsing succeeded. Parameter objects is an array containing 
    // NSDictionaries representing a type "object".

    // Save into Core Data:
    // Create a managed object context, which is a child of the 
    // "main context" of a Core Data stack:
    NSManagedObjectContext* moc = [[NSManagedObjectContext alloc]
                      initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    moc.parentContext = self.coreDataStack.managedObjectContext;
    // Create managed objects and initialize them with the given 
    // NSDictionary:
    for (NSDictionary* object in objects) {
        // note: `createWithParameters:inManagedObjectContext` executes on
        // the context's queue
        [Object createWithParameters:object inManagedObjectContext:moc];
    }
    // Finally, asynchronously save into the persistent store and
    // return the result (a RXPromise):
    return [self.coreDataStack saveWithChildContext:moc]; 
}, nil)
.thenOn(dispatch_get_main_queue(), ^id(id result){
    // Saving to the backing store succeeded. Now, we possibly want to 
    // update some UI on the main thread. We are executing on the main
    // thread already (see thenOn(dispatch_get_main_queue())
    ...
    [self.tableView reloadData];
    return nil;
}, nil)
.then(nil, ^id(NSError* error){
    // If something went wrong in any of the above four steps, the error 
    // will be propagated down and "cought" in this error handler:
    NSLog(@"Error: %@", error);
});

Disclaimer: I'm the author of the library RXPromise available at GitHub. There are a few more Objective-C libraries which implement Promises.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top