1

Trying to improve my coding style and was wondering what the proper way of going about things is. Should they be placed in a NSObjects separate from the view controller and are there any open source clean code examples for me to reference online available?

ChuckKelly
  • 1,742
  • 5
  • 25
  • 54

3 Answers3

2

It's always a good idea to create a model if your app is going to be relying on an construct. I.e if you're building an app which contains a tableview full or photos, it's a good idea to create a model for photos.


Here are a few examples:

Clean Table View Code - Objc.io

In this tutorial, get an understanding of the best way to populate a tableview, and how the relationship works between a model, a cell, and a tableview.

A Weather App Case Study

This is an end-to-end walk through of building a model for your tableview, then populating the tableview.

MVC in Objective-C (II): Model

An overall understanding of how models fit into the MVC pattern.


If you want to construct an object form the JSON response you want to something like this:

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];

// Sanity check
if ([json isKindOfClass:[NSDictionary class]]){
    NSArray *jsonArray = json[@"items"];

    // Sanity check
    if ([jsonArray isKindOfClass:[NSArray class]]){
        // Here you go through all your items one by one
        for (NSDictionary *dictionary in jsonArray) {
            Model *staff = [[Staff alloc] init];
            model.id = [dictionary objectForKey:@"id"];
            model.name = [dictionary objectForKey:@"name"];
            model.attribute = [dictionary objectForKey:@"attribute"]; 
            // Do this for all your attributes

            [arrayContainingObjects addObject:model];
        }
    }
}
MrHaze
  • 3,786
  • 3
  • 26
  • 47
2

As a general rule, it's always a good idea to separate code that accesses a back end server from your UI components. The one best reason being that it's often a requirement for several UI components to access the same server calls.

As far as examples, there are probably thousands. But perhaps a better idea might be to read up on things such as design patterns and app architectural patterns.

objc.io has some good articles on these subjects. Here's another on Medium. There are lots of other, just google search.

drekka
  • 20,957
  • 14
  • 79
  • 135
  • but why is it I NEVER see any code examples of afnetworking requests in NSObjects? – ChuckKelly Mar 09 '16 at 06:42
  • The answer to that would depend on what examples you look at, if it's just a quick tutorial example, then it could be quick and dirty, so they won't need to show how to use a model (NSObject). – MrHaze Mar 09 '16 at 06:57
1

Use common NSObject Class for Calling WS with AFNetworking 2.0 First make NSObject Class with any name here i am creating NSObject Class With name Webservice.h and Webservice.m

Webservice.h

@interface Webservice : NSObject

+ (void)callWSWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure;

@end

Webservice.m your nsobject.m file is look like this.(add two functions in .m file)

#import "Webservice.h"

#define kDefaultErrorCode 12345

@implementation Webservice

+ (void)callWSWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *error))failure {

    [self requestWithUrl:stUrl parmeters:parameters success:^(NSDictionary *response) {
        //replace your key according your responce with "success"
        if([[response objectForKey:@"success"] boolValue]) {
            if(success) {
                success(response);
            }
        }
        else {
            //replace your key according your responce with "message"
            NSError *error = [NSError errorWithDomain:@"Error" code:kDefaultErrorCode userInfo:@{NSLocalizedDescriptionKey:[response objectForKey:@"message"]}];
            if(failure) {
                failure(error);
            }
        }
    } failure:^(NSError *error) {
        if(failure) {

            failure(error);
        }
    }];
}

- (void)requestWithUrl:(NSString *)stUrl parmeters:(NSDictionary *)parameters success:(void (^)(NSDictionary *response))success failure:(void (^)(NSError *))failure {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];

    //remove comment if you  want to use header
    //[manager.requestSerializer setValue:@"" forHTTPHeaderField:@"Authorization"];

    [manager GET:stUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            if(success) {
                success(responseObject);
            }
        }
        else {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if(success) {
                success(response);
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if(failure) {
            failure(error);
        }
    }];}

@end

make sure you have to replace your dictionary key with success and message for handling of responce callback function

Use like this call this common method from any viewcontroller.m and any methods from any viewControllers. for temporary i am using viewDidLoad for calling This WS.

- (void)viewDidLoad {
    [super viewDidLoad];

    NSDictionary *dictParam = @{@"parameter1":@"value1",@"parameter1":@"value2"};

    [WebClient requestWithUrlWithResultVerificationWithLoder:@"add your webservice URL here" parmeters:dictParam success:^(NSDictionary *response) {
        //Success
        NSLog(@"responce:%@",response);
        //code here...

    } failure:^(NSError *error) {
        //Error
        NSLog(@"error:%@",error.localizedDescription);
    }];


}

add your Parameter, values and webservice URL in upper method. you can easyly use this NSObjcet Class. for more details please visit AFNetworking or here.

Community
  • 1
  • 1
Vvk
  • 4,031
  • 29
  • 51
  • I get a no known class method for the first function even though its declared in the .h – ChuckKelly Mar 10 '16 at 11:05
  • @ChuckKelly please write your error in detail. please – Vvk Mar 10 '16 at 11:35
  • A good programmer never writes the same code x2 so shouldn't i find a way to keep failure block contained in this method that makes the request since what should happen is kind of universal in the event of a error. – ChuckKelly Mar 19 '16 at 04:56