正如你们中的一些人所说,它应该可以工作,而且确实如此。我的代码有一些错误。但是我想提供一个小例子来证明这就是正确的方法:
#import "PointersAppDelegate.h"
#import "PointersViewController.h"
#import "ClassA.h"
#import "ClassB.h"
@implementation PointersAppDelegate
@synthesize window=_window;
@synthesize viewController=_viewController;
@synthesize classA, classB;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
classA = [[ClassA alloc] init];
classB = [[ClassB alloc] init];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
[[classA words] addObject:@"two"];
[classB print];
return YES;
}
- (void)dealloc
{
[_window release];
[_viewController release];
[classA release];
[classB release];
[super dealloc];
}
@end
//类 A
@interface ClassA : NSObject {
NSMutableArray *words;
}
@property(nonatomic,retain)NSMutableArray *words;
@end
#import "ClassA.h"
@implementation ClassA
@synthesize words;
- (id)init{
self = [super init];
if (self) {
words = [[NSMutableArray alloc] initWithObjects:@"one", nil];
}
return self;
}
- (void)dealloc {
[words release];
[super dealloc];
}
@end
类B
#import <Foundation/Foundation.h>
@interface ClassB : NSObject {
NSMutableArray *words;
}
@property(nonatomic,retain)NSMutableArray *words;
-(void)print;
@end
#import "ClassB.h"
#import "PointersAppDelegate.h"
@implementation ClassB
@synthesize words;
- (id)init{
self = [super init];
if (self) {
self.words = [[(PointersAppDelegate*)[[UIApplication sharedApplication] delegate] classA] words];
}
return self;
}
-(void)print{
for(int i=0;i<[words count];i++)
NSLog(@"%@", [words objectAtIndex:i]);
}
- (void)dealloc {
[words release];
[super dealloc];
}
@end
结果是:
2011-07-04 12:38:33.759 Pointers[20059:707] one
2011-07-04 12:38:33.767 Pointers[20059:707] two
classB
中的words
属性是否已经被实例化了? - Deepak Danduprolu