我的类别表是空的,我创建了一些类别

时间:2015-03-09 19:23:34

标签: objective-c tableview

我正在建立一个按类别查找应用程序广告的系统,但是在创建我的表后它是空的。我创建了类别,但它们没有出现。

这是我的分类视图:

#import "CategoriesTableViewController.h"
#import "AdViewController.h"
#import "JVWebService.h"
//#import "SearchViewController.h"

#define JVGrayCellColor [UIColor colorWithRed:236/255.0 green:240/255.0 blue:241/255.0 alpha:1]

@interface CategoriesTableViewController ()
@property (strong, nonatomic) NSArray *categoriesArray;
- (IBAction)search:(id)sender;
@end

@implementation CategoriesTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.shouldHaveMenuButton = YES;
}

#pragma mark - Data Source

- (NSArray *)categoriesArray {
    if (_categoriesArray) return _categoriesArray;

    return [NSArray arrayWithObjects:
            @[@"celulares", @"mobile.png"],
            @[@"tablets", @"tablet.png"],
            @[@"eletrônicos", @"eletro.png"],
            @[@"video-games", @"videogame.png"],
            @[@"informática", @"monitor.png"],
            @[@"esportes", @"runner.png"],
            @[@"arte e lazer", @"paint.png"],
            @[@"veículos", @"car.png"],
            @[@"para a casa", @"house.png"],
            @[@"roupas", @"shirt.png"],
            @[@"bebês", @"baby.png"],
            @[@"coisas", @"etc.png"],
            nil];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categoriesArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryCell" forIndexPath:indexPath];

    if (!cell) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CategoryCell"];

    UILabel *categoryName = (UILabel *)[cell viewWithTag:10];

    categoryName.text = [[self.categoriesArray objectAtIndex:indexPath.row][0] uppercaseString];
//    
//    UIImageView *categoryImage = (UIImageView *)[cell viewWithTag:20];
//    categoryImage.image = [UIImage imageNamed:[self.categoriesArray objectAtIndex:indexPath.row][1]];
//    categoryImage.contentMode = UIViewContentModeScaleAspectFit;

    if (indexPath.row %2 != 0)
        cell.backgroundColor = JVGrayCellColor;
    else
        cell.backgroundColor = [UIColor whiteColor];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    [[JVWebService sharedService] getAdsForCategory:indexPath.row];

    AdViewController *adsVC = [[UIStoryboard storyboardWithName:@"Ad" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"AdViewController"];
    [adsVC setLoading:YES];
    [[JVWebService sharedService] setServiceDelegate:adsVC];

    [self.navigationController pushViewController:adsVC animated:YES];
}

#pragma mark - Actions

//- (IBAction)search:(id)sender {
//    SearchViewController *svc = [[UIStoryboard storyboardWithName:@"Search" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"SearchViewController"];
//    
//    [self.navigationController presentViewController:[[UINavigationController alloc] initWithRootViewController:svc]
//                                            animated:YES
//                                          completion:nil];
//}



@end

这是我的WebService;

#import "JVWebService.h"
#import <RestKit/RestKit.h>
#import "AppDelegate.h"
#import "JVUtils.h"
#import "Ads.h"
#import "CategoriesTableViewController.h"

static NSString *kServerURL = @"http://localhost:3000";

@interface JVWebService ()
@property (strong, nonatomic) RKObjectManager *restKitObjectManager;

@end

#define kSuccessStatusCode RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)

@implementation JVWebService

+ (instancetype)sharedService {
    static JVWebService *sharedService = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        sharedService = [[self alloc] init];

        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        sharedService.restKitObjectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:kServerURL]];
        [sharedService.restKitObjectManager.HTTPClient setAuthorizationHeaderWithUsername:[[[AppDelegate sharedDelegate] currentUser] email]
                                                                                 password:[[[AppDelegate sharedDelegate] currentUser] password]];
    });
    return sharedService;
}

#pragma mark - User


- (void)getAdsFromCurrentUser {
    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:Ads.class];
    [objectMapping addAttributeMappingsFromDictionary:self.adAttributes];

    NSString *path = @"/my_ads.json";

    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping
                                                                                            method:RKRequestMethodAny
                                                                                       pathPattern:path
                                                                                           keyPath:@"ads"
                                                                                       statusCodes:kSuccessStatusCode];
    [self.restKitObjectManager addResponseDescriptor:responseDescriptor];
    [self.restKitObjectManager getObjectsAtPath:path parameters:nil success:^(RKObjectRequestOperation *operation,
                                                                              RKMappingResult *result){

        if ([self.serviceDelegate respondsToSelector:@selector(successfulRequestDidReturnObject:)])
            [self.serviceDelegate successfulRequestDidReturnObject:result.array];

    } failure:^(RKObjectRequestOperation *operation, NSError *error){
        RKLogError(@"Operation failed with error: %@", error);

        if ([self.serviceDelegate respondsToSelector:@selector(requestDidFailWithError:)])
            [self.serviceDelegate requestDidFailWithError:error];
    }];

    [self.restKitObjectManager removeResponseDescriptor:responseDescriptor];
}





- (void)postAd:(Ads *)ad {
    NSString *path = @"/ads.json";

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:Ads.class];
    [objectMapping addAttributeMappingsFromDictionary:self.adAttributes];

    RKObjectMapping *requestMapping = [RKObjectMapping requestMapping];
    [requestMapping addAttributeMappingsFromDictionary:self.postAdAttributes];

    RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:requestMapping
                                                                                   objectClass:Ads.class
                                                                                   rootKeyPath:@"ad"
                                                                                        method:RKRequestMethodAny];
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping
                                                                                            method:RKRequestMethodAny
                                                                                       pathPattern:path
                                                                                           keyPath:@"ad"
                                                                                       statusCodes:kSuccessStatusCode];

    [self.restKitObjectManager addRequestDescriptor:requestDescriptor];
    [self.restKitObjectManager addResponseDescriptor:responseDescriptor];

    NSMutableURLRequest *urlRequest = [self.restKitObjectManager multipartFormRequestWithObject:ad method:RKRequestMethodPOST path:path parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

//        NSArray *photosArray = ad.photos[0];
//        for(int i = 0; i < photosArray.count; i++) {
//            
//            NSString *name = [NSString stringWithFormat:@"ad[photos_attributes][%i][picture]", i];
//            NSString *fileName = [NSString stringWithFormat:@"photo%i.jpg", i];
//            [formData appendPartWithFileData:UIImagePNGRepresentation(photosArray[i])
//                                        name:name
//                                    fileName:fileName
//                                    mimeType:@"image/jpg"];
//        }
    }];

    RKObjectRequestOperation *operation = [self.restKitObjectManager objectRequestOperationWithRequest:urlRequest
                                                                                               success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
                                                                                                   if ([self.serviceDelegate respondsToSelector:@selector(successfulRequestDidReturnObject:)])
                                                                                                       [self.serviceDelegate successfulRequestDidReturnObject:nil];

                                                                                               } failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                                                                   if ([self.serviceDelegate respondsToSelector:@selector(requestDidFailWithError:)])
                                                                                                       [self.serviceDelegate requestDidFailWithError:error];
                                                                                               }];
    [self.restKitObjectManager enqueueObjectRequestOperation:operation];

    [self.restKitObjectManager removeRequestDescriptor:requestDescriptor];
    [self.restKitObjectManager removeResponseDescriptor:responseDescriptor];
}



- (NSDictionary *)adAttributes {
    return @{
             @"id" : @"_id",
             @"title" : @"title",
             @"price" : @"price",
             @"local" : @"local",
             @"description" : @"especification",
             @"categories" : @"categories",
             @"photos" : @"photos",
             @"latitude" : @"latitude",
             @"longitude" : @"longitude"
             };
}
- (void)getAdsForCategory:(CategoryType)type {
    NSString *path = @"/category.json";

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:Ads.class];
    [objectMapping addAttributeMappingsFromDictionary:self.adAttributes];

    RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:User.class];
    [userMapping addAttributeMappingsFromDictionary:self.userAttributes];

    [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"user"
                                                                                  toKeyPath:@"owner"
                                                                                withMapping:userMapping]];

    NSString *category = [self categoryStringForType:type];

    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:objectMapping
                                                                                            method:RKRequestMethodAny
                                                                                       pathPattern:path
                                                                                           keyPath:@"ads"
                                                                                       statusCodes:kSuccessStatusCode];


    [self.restKitObjectManager addResponseDescriptor:responseDescriptor];

    NSDictionary *params = @{@"name" : category};

    [self.restKitObjectManager getObjectsAtPath:path parameters:params success:^(RKObjectRequestOperation *operation,
                                                                                 RKMappingResult *result){

        if ([self.serviceDelegate respondsToSelector:@selector(successfulRequestDidReturnObject:)])
            [self.serviceDelegate successfulRequestDidReturnObject:result.array];

    } failure:^(RKObjectRequestOperation *operation, NSError *error){
        RKLogError(@"Operation failed with error: %@", error);

        if ([self.serviceDelegate respondsToSelector:@selector(requestDidFailWithError:)])
            [self.serviceDelegate requestDidFailWithError:error];
    }];

    [self.restKitObjectManager removeResponseDescriptor:responseDescriptor];
}


- (NSString *)categoryStringForType:(CategoryType)type {
    NSString *category;
    switch (type) {
        case CategoryTypeCellphones: category = @"Celulares"; break;
        case CategoryTypeTablets: category = @"Tablets"; break;
        case CategoryTypeElectronics: category = @"Eletronicos"; break;
        case CategoryTypeVideogames: category = @"Video-Games"; break;
        case CategoryTypeComputers: category = @"Informatica"; break;
        case CategoryTypeSports: category = @"Esportes"; break;
        case CategoryTypeHobbies: category = @"Arte e Lazer"; break;
        case CategoryTypeVehicles: category = @"Veiculos"; break;
        case CategoryTypeForHouse: category = @"Para Casa"; break;
        case CategoryTypeClothes: category = @"Roupas"; break;
        case CategoryTypeBabies: category = @"Bebes"; break;
        case CategoryTypeOtherStuffs: category = @"Coisas"; break;
    }
    return category;
}


- (NSDictionary *)postAdAttributes {
    return @{
             @"_id" : @"id",
             @"title" : @"title",
             @"price" : @"price",
             @"local" : @"local",
             @"especification" : @"description",
             @"categories" : @"category_ids",
             @"user_id" : @"user_id",
             @"latitude" : @"latitude",
             @"longitude" : @"longitude"
             };
}

- (NSDictionary *)userAttributes {
    return @{
             @"id" : @"_id",
             @"email" : @"email",
             @"name" : @"name",
             @"avatar" : @"profileImageUrl",
             @"phone" : @"phone",
             @"password" : @"password",
             @"contact_pref" : @"communicationPreference",
             @"products_alerts" : @"productsAlerts"
             };
}

- (NSDictionary *)postUserAttributes {
    return @{
             @"_id" : @"id",
             @"email" : @"email",
             @"name" : @"name",
             @"phone" : @"phone",
             @"password" : @"password",
             @"password" : @"password_confirmation",
             @"communicationPreference" : @"contact_pref"
             };
}
@end

1 个答案:

答案 0 :(得分:0)

TableView需要一个数据源和一个委托(一个提供tableViews数据和委托方法的类)。

这可以在故事板或代码中完成:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.shouldHaveMenuButton = YES;
    self.tableView.delegate = self;
    self.tableView.datasource = self;
}