2015-01-15 1 views
-2

Я пытаюсь вызвать веб-сервис, коллега создал для меня, но я получаю эту ошибку:- [__ NSArrayM objectForKeyedSubscript]: непризнанные селектор направлен например 0x7fb30bf13ac0' ошибки Xcode

-[__NSArrayM objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7fb30bf13ac0' xcode error 

Я новичок для xcode и до сих пор обучения. Простые основные объяснения помогли бы мне сильно

Ниже я приложу мои м и ч файл код

PlayerProgViewController.m файл

#import "PlayerProgViewController.h" 

//step to make the flickrDictionary into a ivar instead of a local variable of the didReceieveData method 
//added a mutable array so we can parse the dictionary and put the objects into the array for use in the tableview 
@interface PlayerProgViewController() 
{ 
    NSDictionary * flickrDictionary; 
    NSMutableArray * cFRAIPArray; 
} 

@end 


@implementation PlayerProgViewController 

@synthesize playerTableView; 

//test for an array for the data to take up 
@synthesize myData; 

//a method that shows the user what is appearing on the screen 
-(void)viewDidLoad 
{ 
    [super viewDidLoad]; 

//to help create the empty array that the data will occupy (TEST) 
//TRYING TO FIX ERROR! (COMMENT OUT FOR NOW) 
    //self.dataArray = [[NSMutableArray alloc]init]; 

//TEST to call web service!!!!! 
    NSURL * myURL = [NSURL URLWithString:@"http://1.1.1.20:8080/Andrews/players"]; 
    NSURLRequest * myRequest = [NSURLRequest requestWithURL:myURL]; 
    NSURLConnection * myConnection = [NSURLConnection connectionWithRequest:myRequest delegate:self]; 
    } 


//TEST to call web service!!!!!...HERE TO.. 
//this method displays an error code or sends data if an error occurs or not 
//if the response recieved is good, the server begins to send data 
//if good goes to didRecieveData method 
//if an error occurs then goes to didFailWithError method 
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
//with the webservice availble, goes here from _dataarray 
    NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *)response; 
    int errorCode = httpResponse.statusCode; 
    NSString * fileMIMEType = [[httpResponse MIMEType]lowercaseString]; 
    NSLog(@"response is %d, %@",errorCode, fileMIMEType); 
} 

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSLog(@"data is %@",data); 

    //shows the same result in our web browser that we want to call 
    //next step to put it in an IOS object so we can pass it around and do whatever we want with it 
    NSString * myString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; 
    NSLog(@"string is %@",myString); 

    //steps to GET the data (putting it in an object) 
    //this manipulates the data from the web page to a NSDictionary 
    //NSError * e = nil; 

    //NSDictionary * ..not needed since we declared the dicitonary on top 
    flickrDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; 

    NSLog(@"dictionary is %@",flickrDictionary); 

//dummy code 
    /* 
    flickrDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&e]; 
    if(![flickrDictionary isKindOfClass:[NSDictionary class]]) 
    { 
     //handle error 
    } 
    else 
    { 
     //NSArray * newArray = flickrDictionary[@"TeamRosterProject"]; 
     //OR 
     cFRAIPArray = flickrDictionary[@"TeamRosterProject"]; 
    } 
    */ 



} 

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    //to inform the user 
    NSLog(@"Connection failed! Error - %@ %@", 
      [error localizedDescription], 
      [[error userInfo]objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 


-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    //do something with the data 
    //receivedData is declared as a method instance elsewhere 
    NSLog(@"Succeeded!"); 

    //now we parse the dictionary only once it is fully populated from the web fetch 
    //originally 12 was set as 5 
    cFRAIPArray = [[NSMutableArray alloc]initWithCapacity:12]; 
    for (NSString * key in flickrDictionary){ 
     NSLog(@"the key is %@",flickrDictionary[key]); 
//APP CRASHES HERE!!!!!!=============================== 
     id object = flickrDictionary[key]; 

     if ([object isKindOfClass:[NSDictionary class]]) { 

      //use firstName to replace _content? 
      //firstName is the valueForKey? 
      NSLog(@"object valueForKey is %@",[object valueForKey:@"_content"]); 
      [cFRAIPArray addObject:[object valueForKey:@"_content"]]; 




     }else{ 
      [cFRAIPArray addObject:flickrDictionary[key]]; 
     } 
    } 

    NSLog(@"cfraiparray %@", cFRAIPArray); 
    [self.playerTableView reloadData]; 
} 


//...HERE 

//these methods are called every time the view will do this or that 
//views appear many times but are only loaded once 
-(void)viewWillAppear:(BOOL)animated{ 
} 
-(void)viewDidAppear:(BOOL)animated{ 
} 
-(void)viewWillDisappear:(BOOL)animated{ 
} 

//required methods in a tableview 
//all called once,but didSelectRow..gets called many times 
/* 
numberOfSectionsInTableView 
numberOfRowsInSection 
cellForRowAtIndexPath 
//set here? 
didSelectRowAtIndexPath 
*/ 


#pragma mark - UITableView Data Source 
//UITableView Delegate requires the 3 methods below! 

//TRYING TO FIX ERROR! (COMMENT OUT FOR NOW) 
/* 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
    { 
     return 1;//return the number of sections 
    } 
*/ 

//TRYING TO FIX ERROR! (COMMENT OUT FOR NOW) 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
    { 
     //??????why as _dataArray and not as dataArray 
//PAUSES HERE AND NOTHING IS RETURNED (POINT OF ERROR) 
     return [_dataArray count]; 
     //return the number of rows in the section 
     //if you are serving data from an array, return the length of the array 
     //categorry is the name of the array 
    } 



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowIndexPath:(NSIndexPath *)indexPath{ 
     static NSString *MyIdentifier = @"Identifier"; 

    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; 
     if(cell==nil){ 
      cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier]; 
     } 


    //OLD WAY TO SET DATA IN THE TABLE 
    //[cell.textLabel setText:[dict valueForKey:@"TeamID"]]; 


//sets data for this cell (needed?) 
    /* 
    cell.textLabel.text = [_dataArray objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.text = @"More text"; 
    cell.imageView.image = [UIImage imageNamed:@"name of image.png"]; 
    //sets the accessory view 
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    */ 

    return cell; 


    //keep this 
    cell.textLabel.text = [cFRAIPArray objectAtIndex:indexPath.row]; 
//used to set data to the detail text label (save for later) 
    cell.detailTextLabel.text = [cFRAIPArray objectAtIndex:indexPath.row]; 

    } 



@end 

PlayerProgViewController.h файл

#import <UIKit/UIKit.h> 

//(test) 
/* 
@protocol PlayerModelProtocol <NSObject> 
-(void)itemsDownloaded:(NSArray *)items; 
@end 
*/ 

@interface PlayerProgViewController : UIViewController <UITableViewDataSource,UITableViewDelegate> 


//(test2) continued 
/* 
@interface PlayerModelProtocol:NSObject 
@property (nonatomic, weak) id<PlayerModelProtocol> delegate; 
-(void)downloadItems; 
*/ 


//@property (strong,nonatomic)NSArray * myPlayerData; 

@property (weak, nonatomic) IBOutlet UITableView *playerTableView; 

@property NSMutableArray * dataArray; 

//contains all the data i created (TEST) 
@property (strong, nonatomic) NSArray * myData; 

//SETTING PROPERTIES (testing with firstName) 
//@property (nonatomic, strong)NSString * firstName; 



@end 

здесь, где приложение нарушает

NSLog(@"the key is %@",flickrDictionary[key]); 

     id object = flickrDictionary[key]; 
+1

Пожалуйста, добавьте контрольную точку исключения в свой проект и покажите только соответствующий код. –

+0

Поверхностный ответ заключается в том, что вы считаете, что у вас есть словарь, но объект, получающий сообщение, действительно представляет собой массив. Попробуйте записать значение '[flickrDictionary class]'. –

+0

Возможный дубликат [Как отлаживать «непризнанный селектор, отправленный на экземпляр») (http://stackoverflow.com/questions/25853947/how-can-i-debug-unrecognized-selector-sent-to-instance-error) –

ответ

1

Вы получаете массив. Итак, итерации по массиву:

for (NSDictionary * player in flickrArray) // The former flickrDictionary, rename it 
{ 
    NSLog(@"the player is %@",player); 

    if ([player isKindOfClass:[NSDictionary class]]) 
    { 
    NSLog(@"object valueForKey is %@",[player valueForKey:@"_content"]) 
… 
    } 
} 
+0

Что я получаю это: словарь ( { ПгвЬЫате = Behr; LastName = Снеки; playerId = 26; }, – Drew

+1

Нет, вы не получите словарь: 1. Посмотрите на описание исключения, 2. ('в начале говорит:« Array! » –

+0

ok, поэтому я получаю массив. Поэтому мне нужен способ вызвать словарь, исправить? Или изменить массив на словарь. – Drew