Best architectural approaches for building iOS networking applications (REST clients)

后端 未结 13 1146
-上瘾入骨i
-上瘾入骨i 2020-12-22 14:11

I\'m an iOS developer with some experience and this question is really interesting to me. I saw a lot of different resources and materials on this topic, but nevertheless I\

13条回答
  •  北海茫月
    2020-12-22 14:56

    I avoid singletons when designing my applications. They are a typical go to for a lot of people but I think you can find more elegant solutions elsewhere. Typically what I do is a build out my entities in CoreData and then put my REST code in an NSManagedObject category. If for instance I wanted to create and POST a new User, I'd do this:

    User* newUser = [User createInManagedObjectContext:managedObjectContext];
    [newUser postOnSuccess:^(...) { ... } onFailure:^(...) { ... }];
    

    I use RESTKit for the object mapping and initialize it at start up. I find routing all of your calls through a singleton to be a waste of time and adds a lot of boilerplate that isn't needed.

    In NSManagedObject+Extensions.m:

    + (instancetype)createInContext:(NSManagedObjectContext*)context
    {
        NSAssert(context.persistentStoreCoordinator.managedObjectModel.entitiesByName[[self entityName]] != nil, @"Entity with name %@ not found in model. Is your class name the same as your entity name?", [self entityName]);
        return [NSEntityDescription insertNewObjectForEntityForName:[self entityName] inManagedObjectContext:context];
    }
    

    In NSManagedObject+Networking.m:

    - (void)getOnSuccess:(RESTSuccess)onSuccess onFailure:(RESTFailure)onFailure blockInput:(BOOL)blockInput
    {
        [[RKObjectManager sharedManager] getObject:self path:nil parameters:nil success:onSuccess failure:onFailure];
        [self handleInputBlocking:blockInput];
    }
    

    Why add extra helper classes when you can extend the functionality of a common base class through categories?

    If you're interested in more detailed info on my solution let me know. I'm happy to share.

提交回复
热议问题