2010-06-14 4 views
0

배열을 RootViewController에서 초기화하고 배열에 addsObjects 메서드를 초기화했습니다. 내 SecondViewController에서 RootViewController 개체를 만들었습니다. 이 메서드는 실행 (메시지를 출력)하지만 배열에 아무 것도 추가하지 않으며 배열이 비어있는 것처럼 보입니다. 아래 코드는 어떤 제안입니까?RootViewController의 메서드가 배열을 저장하지 않습니다.

RootViewController.h

#import "RootViewController.h" 
#import "SecondViewController.h" 

@implementation RootViewController 
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    myArray2 = [[NSMutableArray alloc] init]; 

    NSLog(@"View was loaded"); 
} 
-(void)addToArray2{ 
    NSLog(@"Array triggered from SecondViewController"); 
    [myArray2 addObject:@"Test"]; 
    [self showArray2]; 
} 

-(void)showArray2{ 
    NSLog(@"Array Count: %d", [myArray2 count]); 
} 
-(IBAction)switchViews{ 
    SecondViewController *screen = [[SecondViewController alloc] initWithNibName:nil bundle:nil]; 
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
    [self presentModalViewController:screen animated:YES]; 
    [screen release]; 
} 

SecondViewController.m

편집 ************* 매트의 코드와

나는 다음과 같은 오류가 발생했습니다

#import "SecondViewController.h" 
#import "RootViewController.h" 

@implementation SecondViewController 

-(IBAction)addToArray{ 

    RootViewController *object = [[RootViewController alloc] init]; 
    [object addToArray2]; 

} 
-(IBAction)switchBack{ 
    [self dismissModalViewControllerAnimated:YES]; 
} 

:

"RootViewController '앞에"expected specifier-qualifier-list "가 입력되었습니다."

답변

0

여기에는 매우 중요한 기본 사항이 빠져 있습니다. SecondViewController에 새로운 RootViewController를 할당하면 SecondViewController를 생성하는 데 사용한 것과 동일한 인스턴스가 아니므로 객체를 추가 할 배열에 대한 참조가 없습니다. 당신이하려는 것은 효과가 없을 것입니다. RootViewController에 대한 SecondViewController에서 ivar을 만든 다음 두 번째보기에서 액세스해야합니다. 이런 식으로 뭔가 :

-(IBAction)switchViews{ 
    SecondViewController *screen = [[SecondViewController alloc] 
             initWithNibName:nil bundle:nil]; 
    screen.modalTransitionStyle = UIModalTransitionStyleCoverVertical; 
    [screen setRootViewController:self]; 
    [self presentModalViewController:screen animated:YES]; 
    [screen release]; 
} 

귀하의 바르가 SecondViewController.h에서 다음과 같이 선언해야합니다 : 다음

@property (nonatomic, retain) RootViewController *rootViewController; 

그리고

나서하는 .m 합성, 당신의 바르에 액세스 할 수 있습니다 SecondContController 내에서 :

-(IBAction)addToArray{ 
    [[self rootViewController] addToArray2]; 
} 
+0

내가 물어 보겠다. [screen setRootViewController : self]는 무엇을합니까? 내가 생각하기에,이 코드 라인은 SecondViewController nib가로드 될 때 RootViewController를 네이티브 컨트롤러로 만듭니다. – Tony

+0

단순히 SecondViewController에 RootViewController에 대한 참조를 제공하여 사용자가 작성한 -addToArray2 메서드를 호출하고 호출 할 수 있습니다. 네이티브 * 컨트롤러가 무슨 뜻인지 모르겠습니다. –

+0

내 혼란을 없애 주셔서 감사합니다 :) 나는 이것을 시도 할 것입니다. 설명해 주셔서 감사합니다. – Tony

관련 문제