问题使用不同类的方法

时间:2011-02-14 00:10:41

标签: objective-c cocoa

我有一个问题,我有这个课程:

MainViewController.m
MainViewController.h
Myapp.m
Myapp.h

我想在MainViewController.m中使用Myapp.m中声明的方法“restanswer”,这是代码:

//MyApp.h @class MainViewController;

@interface MyApp : DEFINE_SUPERCLASS // << @todo note to OP: define your superclass. you rarely need to create a root class in objc.
{
  NSMutableArray * answer;
}

@property (nonatomic, retain) NSMutableArray *answer;
- (NSMutableArray *) restarray;

@end

//MyApp.m
#import "MainViewController.h"

@implementation Myapp

@synthesize answer;

NSMutableArray * answer = nil;

- (NSMutableArray *)restarray {
  answer = [[NSMutableArray alloc] initWithObjects:@"1", @"2",@"3", nil];
  return answer;
}

//MainViewController.m
#import "MyApp.h"


@implementation MainViewController

@synthesize answer;

static Myapp * risposte;

-(void).......{
  NSMutableArray * prova = [risposte restarray];
  int numbertest = [prova count];
  NSLog(@"the value is: %d", numbertest);
}

我没有错误,但是numbertest的值是:0,为什么?我的数组有3个对象,请帮帮我...对不起格式代码我尝试但不起作用...

1 个答案:

答案 0 :(得分:1)

...

+ (MyApp *)sharedRiposte
{
// ok -- your OP is lacking (requested) detail
// i have to infer some things:
// 1) MyApp is an NSApplication or UIApplication subclass
// 2) your program actually has designated MyApp as the app's type

 --- if OS X ---
   MyApp * app = (MyApp*)[NSApplication sharedApplication];
   if (![app isKindOfClass:[MyApp class]]) {
     assert(0 && "oops, the app type is not defined correctly");
     return nil;
   }
   else {
     return app;
   }
 --- if iOS ---
   MyApp * app = (MyApp*)[UIApplication sharedApplication];
   if (![app isKindOfClass:[MyApp class]]) {
     assert(0 && "oops, the app type is not defined correctly");
     return nil;
   }
   else {
     return app;
   }
}

-(void).......{
  MyApp * riposte = [[self class] sharedRiposte];
  assert(risposte && "oops, app is not configured properly (assuming MyApp is an NS/UI-Application subclass)");

  NSMutableArray * prova = [risposte restarray];
  assert(prova && "oops, risposte could not create the restarray");

  int numbertest = [prova count];

  // we know the answer to this based on the *current* implementation of restarray
  assert(3 == numbertest && "oops, the array is not what we expect");

  NSLog(@"the value is: %d\nthe array is: %@", numbertest, prova);
}