1

我试图弄清楚如何访问和显示来自在我的 AppDelegate 中创建的 NSMutable 数组中的对象的信息。

从我的 AppDelegate.h

@property (readonly, retain) NSMutableArray *myRaces;
@end
AppDelegate * appDelegate;

从我的 AppDelegate.m

extern AppDelegate * appDelegate;
@synthesize myRaces;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
appDelegate = self;
TheRace * orc;
orc = [[TheRace alloc] init];
orc.raceTitle = @"Orc"; [orc modifyStatsFromRace:(NSString*)orc.raceTitle];
NSLog(@" test %d ", orc.massMod);
orc.raceData = @"Orcs are big burly stupid beasts";
myRaces = [[NSMutableArray alloc] init];
[myRaces addObject:orc];
}

我想从另一个类中调用 orc.massMod 的值,但无法弄清楚如何。我试过。

appDelegate.raceSelected = @"Orc";
NSLog(@"Orc");
appDelegate.theMass = appDelegate.myRaces.orc.massMod;

但是,“appDelegate.theMass = appDelegate.myRaces.orc.massMod;” 失败,错误提示...在对象类型“NSMutableArray *”上找不到属性“orc”

我如何称呼该信息?我想显示 massMod 的值,它在 appDelegate 内的 NSLog 中工作。“appDelegate.theMass”是在我的 UILabel 中显示的价值所在。

4

3 回答 3

1

由于您存储orc在数组中,因此无法通过变量名称访问它。您应该能够通过调用来检索它objectAtIndex,例如

appDelegate.theMass = ((TheRace*)[appDelegate.myRaces objectAtIndex:0]).massMod;
于 2013-04-16T08:12:57.063 回答
1

当您在 Appdelegate 的另一个类中并调用“appDelegate.myRaces”时,您会得到一个 NSMutableArray。因此,您不能通过附加“.orc”来访问 orc 对象,因为 orc 不是 NSMutableArray 的属性。

你可以改写

// The cast is not necessary, but is useful for readability
TheRace * myOrc = (TheRace*)[appDelegate.myRaces objectAtIndex:0];  
appDelegate.theMass = myOrc.massMod;

但是您很容易忘记哪个项目与哪个索引一起使用。您也可以使用 NSMutableDictionary :

-在你的 AppDelegate.h

@property (readonly, retain) NSMutableDictionary *myRaces;

- 在您的 AppDelegate.m 中:

myRaces = [[NSMutableDictionary alloc] init];
[myRaces setObject:orc forKey:@"Orc"];

-在你的其他课程中:

TheRace * myOrc = (TheRace*)[appDelegate.myRaces objectForKey@"Orc"];  
appDelegate.theMass = myOrc.massMod;
于 2013-04-16T09:04:01.117 回答
0

定义这样的宏的最佳方法:

#define MyAppDelegateObject ((AppDelegate *)[[UIApplication sharedApplication] delegate])

并像这样在 appdelegate 中引用您的属性:

NSLog(@"Races: %@",MyAppDelegateObject.myRaces);
于 2013-04-16T08:07:30.647 回答