从另一个类访问NSArray

时间:2011-10-07 17:31:14

标签: iphone objective-c xcode macos

  

可能重复:
  IOS: call a method in another class

如何将NSArray对象传递给另一个类?我不想使用extern来访问它,那么还有其他方法可以实现吗?

另请注意,我是初学者

1 个答案:

答案 0 :(得分:2)

在此示例中,tableDataSourceNSArray,可以作为类的属性进行访问。

interface声明(iPadTableWithDetailsViewController.h)中:

@interface iPadTableWithDetailsViewController : UIViewController {
    NSArray *tableDataSource;
}

@property (nonatomic, retain) NSArray *tableDataSource;

然后,在implementation定义(iPadTableWithDetailsViewController.m)中:

#import "iPadTableWithDetailsViewController.h"

@implementation iPadTableWithDetailsViewController

@synthesize tableDataSource;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        self.tableDataSource = nil;
    }
    return self;
}

- (void)viewDidLoad {
    if (!tableDataSource) {
        self.tableDataSource = [NSArray array];
    }
}

.....

@end

然后你可以从另一个类中访问它:

- (void)doSomething {
    iPadTableWithDetailsViewController *myViewController = [[iPadTableWithDetailsViewController alloc] initWithNibName:@"iPadTableWithDetailsViewController" bundle:nil];
    myViewController.tableDataSource = [NSArray arrayWithObjects:@"object1", @"object2", nil];
    NSLog(@"myViewController.tableDataSource: %@", [myViewController.tableDataSource description];
}

更多信息和示例:

Properties in Objective-C
Tutorial: Using Properties in Objective-C
cocoadevcentral learn objective-c