2012-01-06 3 views
0

В UITableViewController, под didSelectRowAtIndexPath, я установил свойство в файле NSObject к значению. Я могу использовать NSLog и видеть, что переменная действительно была установлена. Однако, когда я использую представление таблицы и нажимаю на ячейку, которая активирует didSelectRowAtIndexPath, я заметил, что переменная устанавливает себя равной нулю, когда представление изменяется на другой UITableViewController. Я даже сделал NSLog под viewDidLoad, чтобы проверить это значение свойства, и он вернул нуль. Почему это? Как я могу это сделать, чтобы он не изменился до нуля?Почему моя переменная сама настраивается на нуль?

Первый UITableView.m:

#import "enchantmentViewController.h" 
#import "levelViewController.h" 
#import "dataBrain.h" 

@interface enchantmentViewController() 

@property (nonatomic, strong) dataBrain *brain; 
@property (nonatomic, strong) levelViewController *level; 

@end 

@implementation enchantmentViewController 

@synthesize brain = _brain; 
@synthesize level = _level; 

- (dataBrain *)brain 
{ 
    if (!_brain){ 
     _brain = [[dataBrain alloc] init]; 
    } 
    return _brain; 
} 

- (levelViewController *)level 
{ 
    if (!_level){ 
     _level = [[levelViewController alloc] init]; 
    } 
    return _level; 
} 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // 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)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    //warning Potentially incomplete method implementation. 
    // Return the number of sections. 
    return [self.brain enchantmentNumberOfSections]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    //#warning Incomplete method implementation. 
    // Return the number of rows in the section. 
    return [self.brain enchantmentNumberOfCells:section]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"enchantment"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (!cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    cell.textLabel.text = [self.brain enchantmentCellText:indexPath]; 

    return cell; 

} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    return [self.brain enchantmentSectionData:section]; 
} 


/* 
// Override to support conditional editing of the table view. 
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the specified item to be editable. 
    return YES; 
} 
*/ 

/* 
// Override to support editing the table view. 
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if (editingStyle == UITableViewCellEditingStyleDelete) { 
     // Delete the row from the data source 
     [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    } 
    else if (editingStyle == UITableViewCellEditingStyleInsert) { 
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
    } 
} 
*/ 

/* 
// Override to support rearranging the table view. 
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath 
{ 
} 
*/ 

/* 
// Override to support conditional rearranging of the table view. 
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    // Return NO if you do not want the item to be re-orderable. 
    return YES; 
} 
*/ 

#pragma mark - Table view delegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    [self.brain convertSelectedTableCellToNumberOfPossibleEnchantments:indexPath]; 
    [self.brain test]; 
} 

@end 

Второй UITableViewController код:

#import "levelViewController.h" 
#import "dataBrain.h" 

@interface levelViewController() 

@property (nonatomic, strong) dataBrain *brain; 

@end 

@implementation levelViewController 

@synthesize brain = _brain; 


- (dataBrain *)brain 
{ 
    if (!_brain){ 
     _brain = [[dataBrain alloc] init]; 
    } 
    return _brain; 
} 

- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // 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)viewDidUnload 
{ 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    // Return the number of sections. 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    //NSLog(@"needing sections"); 

    NSLog(@"value: %@", [self.brain levelNumberOfCells]); 
    return [self.brain.numberOfLevelsForCurrentEnchantment integerValue]; 
    //[self.brain levelNumberOfCells]; 

} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"level"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (!cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    cell.textLabel.text = @"jo";//[self.brain levelCellText:indexPath]; 

    return cell; 
} 

@end 

[self.brain test] возвращает значение переменной, о котором идет речь.

+0

Это может быть глупый вопрос: что такое «файл NSObject»? –

+0

Новый файл, который является подклассом NSObject, извините за то, что вы не поняли этого. – blake305

+0

Опубликуйте код, это поможет нам. – esqew

ответ

1

Таким образом, каждый viewController имеет свой собственный мозг, который автоматически выделяется при необходимости. Вы устанавливаете переменную в одном мозгу VC, затем переключаете VC, так что теперь, когда вы просите что-то о своем мозгу, вы спрашиваете о другом мозге - в котором вы не вносили никаких изменений.

+0

Ну, как xcode знает, что мозг предназначен только для определенного VC? Не могу ли я использовать ту же модель для двух контроллеров? – blake305

+0

Вы МОЖЕТЕ, но вы не сделали: как реализовано, каждый ВК выделяет свой собственный мозг. Я ничего не вижу в вашем коде, который получает мозг от одного VC к другому, а не к глобальному, к которому относятся оба. –

+0

'[self.brain convertSelectedTableCellToNumberOfPossibleEnchantments: indexPath];' устанавливает свойство в модели и 'NSLog (@" значение:% @ ", [self.brain levelNumberOfCells]);' предполагается регистрировать значение свойства. – blake305

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