OGeek|极客世界-中国程序员成长平台

标题: ios - objective-c "callback" [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:26
标题: ios - objective-c "callback"

我是 Objective C 的新手。现在我正在开发我的新应用程序,我对回调函数有一些疑问。

所以这是我的场景:

我有一个名为 Person 的 NSObject 类,它(显然)代表一个人。 这个类有一些参数,比如:人名、人名等。 在 Person.m 中,我有一个函数可以调用我的 rest API,检索我需要的所有数据,解析 JSON 响应,创建 Person 对象并将其插入到 NSMutableArray。 这是我的 Person.h 的一个示例:

#import <Foundation/Foundation.h>

@interface Person : NSObject
@property(nonatomic, assign) id delegate;


@property NSString * name;
@property NSString * secondName;


-(void)getPersons;

@end

还有 Person.m 文件:

#import "erson.h"
#import <AFNetworking.h>
#import "ViewController.h"

@implementation Person
@synthesize delegate;

// Call this function to get all persons
-(void)getPersons{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET"www.myApi.com/persons" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *allPersons = [[NSMutableArray alloc]init];
        // Parsing JSON response and getting array with all persons
        allPersons = [self parseaJson:responseObject];
        // Calling my "callback" function in my ViewController.m
        [self.delegate callback:allPersons];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

// This function will parse json response and create array with Person objects
-(NSMutableArray *)parseaJsonNSDictionary *)jsonResponse{
    NSMutableArray *allPersons = [[NSMutableArray alloc]init];
    NSDictionary *resources = [jsonResponse objectForKey"resources"];

    for (NSDictionary *jsonObject in resources) {
        Person *personObject = [[Person alloc]init];
        personObject.name = [jsonObject objectForKey"name"];
        personObject.secondName = [jsonObject objectForKey"secondname"];

        [allPersons addObject:personObject];
    }

    return allPersons;
}

@end

我也有我的 ViewController 类。从我的 ViewController 类中,我调用我的 Person 类以将所有 Person 对象放在一个数组中。 以下是 ViewController.h 的示例:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
    /**
     Array with all Person objects
     */
    NSMutableArray * personsArray;
}


/**
 This function calls when Person.m have finished to retrive all persons from my API
*/
-(void)callbackNSMutableArray *)recivedPersons;

@property (nonatomic, strong) IBOutlet UITableView *table;

@end

还有 ViewController.m :

#import "ViewController.h"
#import "erson.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.delegate = self;
    self.table.dataSource = self;


    // GETTING ALL PERSONS
    Person * myPersonClass = [[Person alloc]init];
    [myPersonClass getPersons];
    myPersonClass.delegate = self; // This line is very important...
}

-(void)callbackNSMutableArray *)recivedPersons{

    personsArray = [[NSMutableArray alloc]initWithArray:lineasBus];
    // Reloading my table
    [self.table reloadData];

}
...
@end

所以,它的工作原理如下:

  1. 从 ViewController.m 我在 Person.m 中调用我的 getPersons 函数
  2. 得到 JSON 响应后,我正在解析它并使用 Person 对象创建数组
  3. 在 ViewController.m 中调用“回调”函数

所有这些都有效,因为我使用委托(delegate),但实际上,我不知道什么是委托(delegate)... 我认为有另一种更专业的方式来实现像我这样的解决方案。 (也许是 block 或类似的东西?)



Best Answer-推荐答案


这是我通常做的。 关于 Person.h

+ (void)personsWithCompletionvoid (^)(NSArray *result, NSError *error))completion;

在你的 Person.m 上

+ (void)personsWithCompletionvoid (^)(NSArray *result, NSError *error))completion{

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET"www.myApi.com/persons" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *allPersons = [[NSMutableArray alloc]init];
        // Parsing JSON response and getting array with all persons
        allPersons = [self parseaJson:responseObject];

//here you call the completion handler
if(completion) completion(allPersosn, error);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

你从 VC 中使用它

[Person personsWithCompletion:^(NSArray *result, NSError *error) {
        if (error == nil) {
            //do stuff
        }
    }];

希望对你有帮助。

关于ios - objective-c "callback",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904801/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4