objective-c - 不同类的方法存在问题

标签 objective-c cocoa

我有一个问题,我有这个类(class):

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 个对象,请帮助我...抱歉,我尝试了格式代码,但不起作用...

最佳答案

...

+ (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);
}

关于objective-c - 不同类的方法存在问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987816/

相关文章:

c++ - Qt 菜单快捷方式在 OS X 上不起作用

ios - Sprite Kit和IOS开发

iphone - iOS 6 - YouTube 应用

objective-c - 在 UIWebView 中为文本字段设置文本

objective-c - 为灰度 NSImage(或 CIImage)着色

ios - 从可变字典中删除对象会引发异常

iphone - NSDate 查找离今天最近的日期

iphone - 到达特定位置时打开 iPhone 应用程序?

cocoa - 在 Mac 上的 Cocoa 中以编程方式流式传输音频

objective-c - 为什么 -isMemberOfClass : not work here?