2013-06-30 3 views
0

Я просто пытаюсь передать NSArray между этими двумя классами, и каждый раз, когда я NSLog, его значение в классе B возвращает NIL.NSArray в классе B возвращает NIL?

Почему это, как я могу получить его для отображения этого UITableView?

Вот класс хиджры

#import <UIKit/UIKit.h> 
#import "Class B.h" 

@class Class B; 

@interface Class A : UIViewController <UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIPopoverControllerDelegate> { 

    IBOutlet UITableView *ToolsTable; 
    IBOutlet UICollectionView *strategyCollection; 
    IBOutlet UIButton *countButton; 
    IBOutlet UIButton *camerButton; 
    IBOutlet UIButton *videoButton; 
    IBOutlet UIButton *textButton; 
    IBOutlet UIButton *probeButton; 
    IBOutlet STPopOverQuestionViewViewController *questionListController; 
    IBOutlet UIPopoverController *questionList; 
    NSMutableDictionary *stratToolsDict; 
    NSMutableArray *stratTools; 
    NSMutableArray *stratObjects; 
    NSMutableDictionary *QuestionDict; 
    NSMutableArray *QuestionsList; 
} 

@property (strong, nonatomic) IBOutlet UIView *strategyOBJView; 
@property (retain, nonatomic) NSMutableDictionary *stratToolsDict; 
@property (retain, nonatomic) NSMutableArray *stratTools; 
@property (retain, nonatomic) NSMutableArray *stratObjects; 
@property (retain, nonatomic) NSMutableDictionary *QuestionDict; 
@property (retain, nonatomic) NSMutableArray *QuestionsList; 

- (IBAction)questionListClick:(id)sender; 

@end 

Класс a.m

#import "STQuestionViewViewController.h" 
#import "STQuestionCreatorViewController.h" 
#import "STPopOverQuestionViewViewController.h" 


@interface STQuestionViewViewController() { 
    NSMutableArray *toolsList; 
    NSArray *strategyData; 
    UIViewController *popOverQuestionView; 
    NSMutableDictionary *stratObjectsDict; 
} 


@end 

@implementation STQuestionViewViewController 
@synthesize QuestionDict; 
@synthesize stratToolsDict; 
@synthesize stratObjects; 
@synthesize stratTools; 
@synthesize QuestionsList; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     toolsList = [[NSMutableArray alloc] init]; 
     NSDictionary *count = [[NSDictionary alloc] initWithObjectsAndKeys:@"Count", @"title",nil]; 
     NSDictionary *camera = [[NSDictionary alloc] initWithObjectsAndKeys:@"Camera",@"title", nil]; 
     NSDictionary *video = [[NSDictionary alloc] initWithObjectsAndKeys:@"Video",@"title", nil]; 
     NSDictionary *text = [[NSDictionary alloc] initWithObjectsAndKeys:@"Text",@"title", nil]; 
     NSDictionary *probe = [[NSDictionary alloc] initWithObjectsAndKeys:@"Probe",@"title", nil]; 

     [toolsList addObject:count]; 
     [toolsList addObject:camera]; 
     [toolsList addObject:video]; 
     [toolsList addObject:text]; 
     [toolsList addObject:probe]; 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    //Question Array Setup and Alloc 
    stratToolsDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:countButton,@"count",camerButton,@"camera",videoButton,@"video",textButton,@"text",probeButton,@"probe", nil]; 
    stratTools = [[NSMutableArray alloc] initWithObjects:@"Tools",stratToolsDict, nil]; 
    stratObjectsDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:stratTools,@"Strat1",stratTools,@"Strat2",stratTools,@"Strat3",stratTools,@"Strat4", nil]; 
    stratObjects = [[NSMutableArray alloc]initWithObjects:@"Strategies:",stratObjectsDict,nil]; 
    QuestionDict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:stratObjects,@"Question 1?",stratObjects,@"Question 2?",stratObjects,@"Question 3?",stratObjects,@"Question 4?",stratObjects,@"Question 5?", nil]; 


    //add strategys to questions 
    QuestionsList = [[NSMutableArray alloc]init]; 
    for (int i = 0; i < 1; i++) { 
     [QuestionsList addObject:QuestionDict]; 
    } 
    NSLog(@"Object: %@",QuestionsList); 

* Я пытаюсь Передайте NSMutableArray QuestionsList; к классу B и присвоить его UITableView DataSource. Который затем возвращается к UIPopOverController, который выделяется и инициализируется в классе А.

класса Bh

#import <UIKit/UIKit.h> 
#import "Class A.h" 

@class Class A; 

@interface Class B : UITableViewController<UITableViewDataSource, UITableViewDelegate> { 
    NSMutableDictionary *Questions; 
    NSMutableArray *QuestionList; 
    Class A *arrayQuestions; 
} 

@property Class A *arrayQuestions; 

@end 

Класс Bm

#import "Class B.h" 
#import "Class A.h" 

@interface Class B() 

@end 

@implementation Class B 
@synthesize arrayQuestions; 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    if ([super initWithStyle:style] != nil) { 

     //Make array 
     arrayQuestions = [[STQuestionViewViewController alloc]init]; 
     QuestionList = [arrayQuestions QuestionsList]; 

     //Log test 
     NSLog(@"QuestionList init method: %@",QuestionList); 
     NSLog(@"QuestionsDict init method: %@",Questions); 

     //Make row selections persist. 
     self.clearsSelectionOnViewWillAppear = NO; 

     //Calculate how tall the view should be by multiplying 
     //the individual row height by the total number of rows. 
     NSInteger rowsCount = [QuestionList count]; 
     NSInteger singleRowHeight = [self.tableView.delegate tableView:self.tableView 
               heightForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; 
     NSInteger totalRowsHeight = rowsCount * singleRowHeight; 

     //Calculate how wide the view should be by finding how 
     //wide each string is expected to be 
     CGFloat largestLabelWidth = 0; 
     for (NSString *colorName in Questions) { 
      //Checks size of text using the default font for UITableViewCell's textLabel. 
      CGSize labelSize = [colorName sizeWithFont:[UIFont boldSystemFontOfSize:20.0f]]; 
      if (labelSize.width > largestLabelWidth) { 
       largestLabelWidth = labelSize.width; 
      } 
     } 

     //Add a little padding to the width 
     CGFloat popoverWidth = largestLabelWidth + 100; 

     //Set the property to tell the popover container how big this view will be. 
     self.contentSizeForViewInPopover = CGSizeMake(popoverWidth, totalRowsHeight); 
    } 

    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    //Log object 
    NSLog(@"View did load: %@",QuestionList); 

    // Uncomment the following line to preserve selection between presentations. 
    // self.clearsSelectionOnViewWillAppear = NO; 

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller. 
    // self.navigationItem.rightBarButtonItem = self.editButtonItem; 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    //Log test 
    NSLog(@"QuestionList Sections Method: %@",QuestionList); 
    NSLog(@"QuestionsDict Sections Method: %@",Questions); 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [QuestionList count]; 
    //Log test 
    NSLog(@"QuestionList Row Method: %@",QuestionList); 
    NSLog(@"QuestionsDict Row Method: %@",Questions); 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //Log test 
    NSLog(@"QuestionList Cell for Row: %@",QuestionList); 
    NSLog(@"QuestionsDict Cell For Row: %@",Questions); 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 

    // Configure the cell... 
    cell.textLabel.text = [QuestionList objectAtIndex:indexPath.row]; 

    return cell;} 


#pragma mark - Table view delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *selectedName = [QuestionList objectAtIndex:indexPath.row]; 



    if ([selectedName isEqualToString:@"Question 1?"]){ 

    } 
    else if ([selectedName isEqualToString:@"Question 2?"]){ 

    } 
    else if ([selectedName isEqualToString:@"Question 3?"]){ 

    } 
    else if ([selectedName isEqualToString:@"Question 4?"]){ 

    } 
    else if ([selectedName isEqualToString:@"Question 5?"]){ 

    } 

} 

@end 

Я прошел через он сам несколько раз и не мог понять, почему он равен NIL в классе B w Я знаю, что его назначают в классе A. Любая помощь очень ценится, я нашел похожие проблемы в Stack Overflow, но они, похоже, не решили мою проблему и не нашли ее в возвращаемом значении NIL.

+1

Это много кода, и в нем есть несколько массивов. Какая строка кода, точно, та, где вы неожиданно получаете «нуль»? –

+0

В классе A есть NSMutableArray * QuestionsList, где я добавляю к нему NSMutableDictionary. Извините за весь код, я попытался посмотреть на него и не мог понять, поэтому я хотел открыть сферу вещей для вопроса. – Keeano

ответ

5

Кажется, что вы делаете новый экземпляр Class A всякий раз, когда вы инициализируете экземпляр Class B, вы сразу же спрашиваете, что новый A для его списка вопросов. Однако в реализации для A вы не настраиваете этот список вопросов до -viewDidLoad, который скоро не будет вызван (поскольку вы не загружаете представление во все ваши методы init). Таким образом, я думаю, что список вопросов будет nil, когда вы начнете B, поэтому список вопросов B - nil.

+0

У меня все еще есть проблемы с этим, а также попытка следовать вашему ответу. Как и где я должен реализовать свой массив? Так что я могу передать его Класу Б из А? – Keeano

+0

Где я должен его инициализировать? Я получаю SIGABRT при попытке инициализировать его в методе Init. – Keeano

Смежные вопросы