![](/img/trans.png)
[英]Accessing an array variable of AppDelegate.m from another ViewController.m
[英]Accessing Class Data Members in ViewController.m (xCode / Objective C)
我有一个类myClass,想访问它的属性,一个NSArray *currentOptions
(特别是要获取currentOptions
的大小并访问我放入其中的NSString)。
我有一个名为generate options的方法,该方法将一个已填充的数组分配给*currentOptions
。 在尝试访问*currentOptions
之前,将调用生成选项。 myClass的实例也已通过App委托添加到ViewController。 但是,在调用buttonOnePressed时,我不断收到此错误:
[myClass currentOptions]:无法识别的选择器已发送到实例0x9b10490
这是我的代码的一部分:
//TClass.h
@interface TClass : NSObject {
NSArray *currentOptions;
}
@property (nonatomic, retain) NSArray *currentOptions;
@end
//viewController
- (IBAction) buttonOnePressed:(id)sender {
NSLog(@"button1 pressed");
NSLog(@"int: %d",[myClass.currentOptions count]);
//myClass here is the instance of TClass
}
有时会导致该错误的一件事是无法正确保留myClass。 (此外:“ myClass”对于指针来说确实是个坏名字,因为指向的对象几乎肯定不是类,而是对象,即类的实例。)如果您不保留myClass指向的对象,它将被释放。 有时,恰好在该位置创建了一个不同的对象,最终您将向原始对象发送一条消息给新对象,该消息是另一种类型,并且不理解该消息。
对于所有关注的人,通过进行以下更改已解决了该问题:
1)综合当前选项TClass.m
@implementation TClass
@synthesize currentOptions;
@end
2)我使currentOptions NSMutableArray而不是NSArray。 这是因为我需要将值重新分配给当前选项。 不知何故,它与NSArray崩溃了,并且一切都可以通过NSMutable数组顺利进行,例如
@implementation TutorialClass
if ([currentOptions count] > 0) {
[currentOptions removeAllObjects];
}
[currentOptions addObject:[options objectAtIndex:0]];
[currentOptions addObject:[options objectAtIndex:1]];
[currentOptions addObject:[options objectAtIndex:2]];
[currentOptions addObject:[options objectAtIndex:3]];
3)当然,我还必须在TClass.m的init方法中执行以下操作
currentOptions = [[NSMutableArray alloc] init];
现在该吃些食物了。 谢谢卡勒布:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.